-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path173.py
More file actions
71 lines (68 loc) · 1.87 KB
/
173.py
File metadata and controls
71 lines (68 loc) · 1.87 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
65
66
67
68
69
70
71
class TreeNode:
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: TreeNode
"""
self.visit=[]
def construct_tree(lst):
if lst is None:
return
head=TreeNode(lst[0])
queue=[]
queue.append(head)
i=0
while i<len(lst):
ele=queue.pop(0)
i=i+1
if i<len(lst) and lst[i] is not None:
new=TreeNode(lst[i])
queue.append(new)
ele.left=new
i=i+1
if i<len(lst) and lst[i] is not None:
new=TreeNode(lst[i])
queue.append(new)
ele.right=new
return head
def inorder(root, visit):
if root is None:
return
# if root.left is None and root.right is None:
# visit.append(root.val)
inorder(root.left, visit)
visit.append(root.val)
inorder(root.right, visit)
root=construct_tree(root)
inorder(root, self.visit)
self.next_index=0
self.len=len(self.visit)
def next(self):
"""
:rtype: int
"""
ans=self.visit[self.next_index]
self.next_index+=1
print(ans)
return ans
def hasNext(self):
"""
:rtype: bool
"""
if self.next_index<self.len:
return True
return False
bSTIterator =BSTIterator([7, 3, 15, None, None, 9, 20])
bSTIterator.next()
bSTIterator.next()
bSTIterator.hasNext()
bSTIterator.next()
bSTIterator.hasNext()
bSTIterator.next()
bSTIterator.hasNext()
bSTIterator.next()
bSTIterator.hasNext()