-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search Tree Iterator.py
More file actions
64 lines (58 loc) · 1.44 KB
/
Copy pathBinary Search Tree Iterator.py
File metadata and controls
64 lines (58 loc) · 1.44 KB
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
60
61
62
63
64
__author__ = 'Martin'
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
if root is None:
return
p = root
self.stack.append(p)
while p.left:
p = p.left
self.stack.append(p)
def hasNext(self):
"""
:rtype: bool
"""
if len(self.stack) != 0:
return True
else:
return False
def next(self):
"""
:rtype: int
"""
s = self.stack.pop()
val = s.val
if len(self.stack) != 0:
p = self.stack[-1]
if s.right is not None:
p.left = s.right
while p.left:
p = p.left
self.stack.append(p)
else:
if s.right is not None:
p = s.right
self.stack.append(p)
while p.left:
p = p.left
self.stack.append(p)
return val
root = TreeNode(10)
root.left = TreeNode(5)
root.left.left = TreeNode(2)
root.left.left.right = TreeNode(3)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(25)
i, v = BSTIterator(root), []
while i.hasNext(): v.append(i.next())
print(v)