LeetCode 173. 二叉搜索树迭代器-Py-栈模拟中序遍历
原题链接
简单
作者:
shiqumi
,
2020-02-19 20:14:30
,
所有人可见
,
阅读 547
思路
用栈模拟中序遍历的代码进行拆分;
每次加子树就是把左子树最左边的一条链加进来;
遍历完左子树,要把右子树加进来。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class BSTIterator:
def __init__(self, root: TreeNode):
self.stk = deque()
# 把根节点最左边的一条链加进来
while root:
self.stk.append(root)
root = root.left
def next(self) -> int:
"""
@return the next smallest number
"""
p = self.stk.pop() # 后进先出,把栈顶元素弹出
res = p.val
p = p.right # 把右子树的最左边的一条链加进来
while p:
self.stk.append(p)
p = p.left
return res
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return len(self.stk) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
# 用栈模拟中序遍历的代码进行拆分
# 每次加子树就是把左子树最左边的一条链加进来
# 遍历完左子树,要把右子树加进来