-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0173-binary-search-tree-iterator.py
More file actions
54 lines (43 loc) · 1.19 KB
/
0173-binary-search-tree-iterator.py
File metadata and controls
54 lines (43 loc) · 1.19 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
# time complexity: O(n)
# space complexity: O(n)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.root = root
self.nodeList = []
self.idx = 0
self.traverse(self.root)
def traverse(self, node: Optional[TreeNode]):
if node is None:
return
self.traverse(node.left)
self.nodeList.append(node.val)
self.traverse(node.right)
def next(self) -> int:
self.idx += 1
return self.nodeList[self.idx - 1]
def hasNext(self) -> bool:
if self.idx > len(self.nodeList) - 1:
return False
return True
# Your BSTIterator object will be instantiated and called as such:
root = TreeNode(7)
root.left = TreeNode(3)
root.right = TreeNode(15)
root.right.left = TreeNode(9)
root.right.right = TreeNode(20)
obj = BSTIterator(root)
print(obj.next())
print(obj.next())
print(obj.hasNext())
print(obj.next())
print(obj.hasNext())
print(obj.next())
print(obj.hasNext())
print(obj.next())
print(obj.hasNext())