LeetCode----Binary Search Tree Iterator

Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.


分析:

编写一个二叉搜索树的迭代器(Iterator)。依据题目条件,不能使用递归,那只能使用非递归程序了。另外,使用中序遍历可以得到升序树中元素。

那题点就在于如何将非递归的升序遍历代码分解成next()和hasNext()两个函数共同完成了。


代码:

# Definition for a  binary tree node
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class BSTIterator(object):
    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.iterator = root
        self.st = []

    def hasNext(self):
        """
        :rtype: bool
        """
        while self.iterator:
            self.st.append(self.iterator)
            self.iterator = self.iterator.left
        if self.st:
            return True
        return False

    def next(self):
        """
        :rtype: int
        """
        p = self.st.pop()
        self.iterator = p.right
        return p.val
        

# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())

你可能感兴趣的:(LeetCode,python,iterator,二叉搜索树)