链接:https://leetcode.cn/problems/kTOapQ/
1.题目说明
实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器:
BSTIterator(TreeNode root) 初始化 BSTIterator 类的一个对象。BST 的根节点 root 会作为构造函数的一部分给出。指针应初始化为一个不存在于 BST 中的数字,且该数字小于 BST 中的任何元素。
boolean hasNext() 如果向指针右侧遍历存在数字,则返回 true ;否则返回 false 。
int next()将指针向右移动,然后返回指针处的数字。
注意,指针初始化为一个不存在于 BST 中的数字,所以对 next() 的首次调用将返回 BST 中的最小元素。
可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 的中序遍历中至少存在一个下一个数字。
就是实现一个二叉搜索树迭代器,包括hasNext和next()方法。
采用中序遍历非递归的方式,就可以轻松求解。先做一道中序遍历的题:94. 二叉树的中序遍历。
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
res = []
stack = collections.deque()
p = root
while p or stack:
if p:
stack.append(p)
p = p.left
continue
p = stack.pop()
res.append(p.val)
p = p.right
return res
可以看到,每次得到下一个节点值,都是在stack.pop()之后,因此next方法就可以先将节点指针p一直置为p.left,再调用stack.pop()获取next。
2.题解
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = collections.deque()
self.p = root
def next(self) -> int:
while self.p:
self.stack.append(self.p)
self.p = self.p.left
self.p = self.stack.pop()
val = self.p.val
self.p = self.p.right
return val
def hasNext(self) -> bool:
return self.p is not None or len(self.stack) > 0