LeetCode 173. Binary Search Tree Iterator - 二叉搜索树(Binary Search Tree)系列题4

Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):

  • BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
  • boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
  • int next() Moves the pointer to the right, then returns the number at the pointer.

Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.

You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.

Example 1:

Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]

Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return False

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 0 <= Node.val <= 106
  • At most 105 calls will be made to hasNext, and next.

 题目要求设计一个基于中序遍历顺序的二叉搜索树的迭代器。要求实现三个接口函数:

  • BSTIterator(TreeNode root) BST迭代器类的构造函数,即初始化类对象。输入是BST的根节点。迭代器一开始不指向任何树里的节点,相当于指向一个比树里所有节点值都小的不存在的数。
  • boolean hasNext() 在遍历过程中迭代器是否还有下一个节点,如果有返回返回True,没有返回False。
  • int next() 迭代器移动到下一个节点并返回节点值。

注1: 迭代器一开始指向一个比树里所有节点值都小的不存在的数,所以首次调用next(),迭代器移动到树里最小的那个节点并返回最小节点值。

注2:每次调用next()保证都有效,即肯定存在至少一个节点,这使得我们在写代码时不需要判断边界条件。

解法:其实就是把二叉搜索树的中序遍历迭代法的代码分开放在几个接口函数里。

  • BSTIterator(TreeNode root) 定义一个堆栈,把从根节点开始树中所有最左侧的节点放入堆栈中,最后堆栈的顶部就是树里的最小节点。
  • boolean hasNext() 只要堆栈不为空就说明存在至少一个节点,返回True
  • int next() 从堆栈弹出一个节点,如果存在右子树,就把右子树的所有左侧节点放入堆栈中,然后返回当前节点值。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        self.stack = []
        while root:
            self.stack.append(root)
            root = root.left

    def next(self) -> int:
        node = self.stack.pop()
        if node.right:
            tmp = node.right
            while tmp:
                self.stack.append(tmp)
                tmp = tmp.left
        return node.val

    def hasNext(self) -> bool:
        return True if self.stack else False

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值