173. Binary Search Tree Iterator
Python
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
tree = []
def inorder(node):
if not node:
return
inorder(node.left)
tree.append(node.val)
inorder(node.right)
inorder(root)
self.root = root
self.tree = tree
self.cur = 0
def next(self) -> int:
result = self.tree[self.cur]
self.cur += 1
return result
def hasNext(self) -> bool:
return self.cur < len(self.tree)