二叉树BST迭代器(非递归中序遍历)——Binary Search Tree Iterator

用栈来实现二叉树的非递归中序遍历

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 not None:
            self.stack.append(cur)
            cur = cur.left
        return node

猜你喜欢

转载自www.cnblogs.com/liqiniuniu/p/10511845.html