-
Notifications
You must be signed in to change notification settings - Fork 3
/
Binary Search Tree Iterator
46 lines (39 loc) · 1.18 KB
/
Binary Search Tree Iterator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator(object):
def __init__(self, root):
"""
:type root: Optional[TreeNode]
"""
self.stack = []
self._leftmost_inorder(root)
def _leftmost_inorder(self, root):
"""
Helper function to traverse the leftmost path of the tree.
"""
while root:
self.stack.append(root)
root = root.left
def next(self):
"""
:rtype: int
"""
# Pop the top element from the stack (smallest available value)
topmost_node = self.stack.pop()
# If the node has a right child, traverse its leftmost subtree
if topmost_node.right:
self._leftmost_inorder(topmost_node.right)
return topmost_node.val
def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()