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 theBSTIterator
class. Theroot
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()
Returnstrue
if there exists a number in the traversal to the right of the pointer, otherwise returnsfalse
.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 tohasNext
, andnext
.
题目要求设计一个基于中序遍历顺序的二叉搜索树的迭代器。要求实现三个接口函数:
BSTIterator(TreeNode root)
BST迭代器类的构造函数,即初始化类对象。输入是BST的根节点。迭代器一开始不指向任何树里的节点,相当于指向一个比树里所有节点值都小的不存在的数。boolean hasNext()
在遍历过程中迭代器是否还有下一个节点,如果有返回返回True,没有返回False。int next()
迭代器移动到下一个节点并返回节点值。
注1: 迭代器一开始指向一个比树里所有节点值都小的不存在的数,所以首次调用next(),迭代器移动到树里最小的那个节点并返回最小节点值。
注2:每次调用next()保证都有效,即肯定存在至少一个节点,这使得我们在写代码时不需要判断边界条件。
解法:其实就是把二叉搜索树的中序遍历迭代法的代码分开放在几个接口函数里。
BSTIterator(TreeNode root)
定义一个堆栈,把从根节点开始树中所有最左侧的节点放入堆栈中,最后堆栈的顶部就是树里的最小节点。boolean hasNext()
只要堆栈不为空就说明存在至少一个节点,返回Trueint 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