-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTIterator.py
More file actions
40 lines (39 loc) · 1.08 KB
/
Copy pathBSTIterator.py
File metadata and controls
40 lines (39 loc) · 1.08 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
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.stack = []
self.buildtree(root)
# @return a boolean, whether we have a next smallest number
def hasNext(self):
l = len(self.stack)
if l > 0:
return True
else:
return False
# @return an integer, the next smallest number
def next(self):
l = len(self.stack)
if l > 0:
node = self.stack.pop()
val = node.val
if node.right != None:
node = node.right
while node:
self.stack.append(node)
node = node.left
return val
def buildtree(self,node):
while node:
self.stack.append(node)
node = node.left
head = TreeNode(2)
head.left = TreeNode(1)
head.right = TreeNode(3)
bsti = BSTIterator(head)
while bsti.hasNext():
print bsti.next()