173. Binary Search Tree Iterator
由题意迭代器要按升序逐一迭代访问,因为二叉搜索树的中序遍历序列就是严格按升序排列的
由此先给出二叉树的中序遍历程序
中序遍历程序:
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
stack = [root]
while root.left: # 一路往左直到最左端
stack.append(root.left)
root = root.left
while stack:
tmp = stack.pop() # 弹出并将访问其值
res.append(tmp.val)
if tmp.right: #
stack.append(tmp.right)
tmp = tmp.right
while tmp.left:
stack.append(tmp.left)
tmp = tmp.left
return res
然后根据中序遍历程序修改为符合本题的程序
Solution:
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = [root]
while root.left:
self.stack.append(root.left)
root = root.left
def next(self) -> int:
tmp = self.stack.pop()
result = tmp.val
if tmp.right:
self.stack.append(tmp.right)
tmp = tmp.right
while tmp.left:
self.stack.append(tmp.left)
tmp = tmp.left
return result
def hasNext(self) -> bool:
return self.stack
请细心比较两程序