forked from ely-mitu/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BSTIterator.py
39 lines (30 loc) · 891 Bytes
/
BSTIterator.py
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
# straight forward solution: do a inorder traversal
class BSTIterator(object):
def __init__(self, root):
self.inorder = []
def helper(root):
if root:
helper(root.left)
self.inorder.append(root.val)
helper(root.right)
helper(root)
def hasNext(self):
return len(self.inorder) != 0
def next(self):
return self.inorder.pop(0)
# Alternative solution:
class BSTIterator(object):
def __init__(self, root):
self.stack = []
while root:
self.stack.append(root)
root = root.left
def hasNext(self):
return len(self.stack) != 0
def next(self):
node = self.stack.pop()
x = node.right
while x:
self.stack.append(x)
x = x.left
return node.val