LeetCode 173. 二叉搜索树迭代器

173. 二叉搜索树迭代器

Difficulty: 中等

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

示例:

BSTIterator iterator = new BSTIterator(root);
iterator.next();    // 返回 3
iterator.next();    // 返回 7
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 9
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 15
iterator.hasNext(); // 返回 true
iterator.next();    // 返回 20
iterator.hasNext(); // 返回 false

提示:

  • next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 _h _是树的高度。
  • 你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。

Solution

Language: 全部题目

二叉排序树的左子树上的节点均小于右子树的节点,放在树里面任意一个节点都成立。根据题意,实际上就是需要你实现二叉搜索树的中序遍历,并且要求时间复杂度为 O(1),并使用 O(h) 内存。

对于二叉树的遍历一般有深度优先和广度优先,深度优先搜索一般结合栈实现,广度优先搜索一般结合队列实现,掌握这两个公式能解决大部分树的题目。因为题目要求使用 O(h) 内存,所以我们要使用深度优先搜索加栈来实现,栈的最大内存使用为树的深度。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
​
class BSTIterator:
    # 二叉树的中序遍历
    def __init__(self, root: TreeNode):
        self.stack = []
        self.helper(root)
​
    def next(self) -> int:
        """
        @return the next smallest number
        """
        while self.stack:
            tmpNode = self.stack.pop()
            if tmpNode.right:
                self.helper(tmpNode.right)
            return tmpNode.val
​
    def hasNext(self) -> bool:
        """
        @return whether we have a next smallest number
        """
        return len(self.stack) > 0
        
    def helper(self, root):
        while root:
            self.stack.append(root)
            root = root.left
​
​
​
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
原文地址:https://www.cnblogs.com/swordspoet/p/14067751.html