Python3
树
深度优先搜索
通过中序遍历二叉搜索树得到的关键码序列是一个递增序列。
这是二叉搜索树的一个重要性质,巧妙利用这一性质可以解决一系列二叉搜索树问题。
本系列以以下非递归中序遍历代码为核心,解决一系列相关问题。
p = root
st = [] # 用列表模拟实现栈的功能
while p is not None or st:
while p is not None:
st.append(p)
p = p.left
p = st.pop()
proc(p.val)
p = p.right
一 二叉搜索树迭代器
(一)算法思路
中序遍历二叉树
(二)算法实现
class BSTIterator:
def __init__(self, root: TreeNode):
self.root = root
self.st = []
self.current = self.root
def next(self) -> int:
"""
@return the next smallest number
"""
while self.current is not None or self.st:
while self.current is not None:
self.st.append(self.current)
self.current = self.current.left
self.current = self.st.pop()
node = self.current
self.current = self.current.right
return node.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self.current or sel