二叉樹BST叠代器(非遞歸中序遍歷)——Binary Search Tree Iterator
阿新 • • 發佈:2019-03-11
tor col 初始化 turn clas return sta style stack
用棧來實現二叉樹的非遞歸中序遍歷
1、棧初始化:從根節點出發一路向左,將一路上的節點push到棧中
2、取next並進行棧的調整:從stack棧頂pop出來的節點即為要取的next節點。如果該節點有右孩子,則從該節點出發,往右走一步,再一路向左,將一路上的節點push進棧。
class BSTIterator: """ @param: root: The root of binary tree. """ def __init__(self, root): self.stack = [] while root != None: self.stack.append(root) root= root.left """ @return: True if there has next node, or false """ def hasNext(self): return len(self.stack) > 0 """ @return: return next node """ def next(self): node = self.stack.pop() cur = node.right while cur is notNone: self.stack.append(cur) cur = cur.left return node
二叉樹BST叠代器(非遞歸中序遍歷)——Binary Search Tree Iterator