-
Notifications
You must be signed in to change notification settings - Fork 0
/
173.py
59 lines (53 loc) · 1.24 KB
/
173.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.st = []
self.root = root
def hasNext(self):
"""
:rtype: bool
"""
if self.st or self.root:
return True
else:
return False
def next(self):
"""
:rtype: int
"""
while self.root:
self.st.append(self.root)
self.root = self.root.left
p = self.st.pop()
self.root = p.right
return p.val
# this is another similiar solution, also good
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
curr = root
while curr is not None:
self.stack.append(curr)
curr = curr.left
def hasNext(self):
"""
:rtype: bool
"""
return bool(self.stack)
def next(self):
"""
:rtype: int
"""
curr = self.stack.pop()
val = curr.val
if curr.right:
curr = curr.right
while curr:
self.stack.append(curr)
curr = curr.left
return val