-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path173.py
80 lines (66 loc) · 2.07 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
__________________________________________________________________________________________________
sample 72 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
while root:
self.stack.append(root)
root = root.left
def next(self) -> int:
"""
@return the next smallest number
"""
node = self.stack.pop()
x = node.right
while x:
self.stack.append(x)
x = x.left
return node.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
__________________________________________________________________________________________________
sample 19496 kb submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.traverse(root)
def traverse(self, root):
if root:
self.traverse(root.left)
self.stack.append(root.val)
self.traverse(root.right)
self.stack.sort()
def next(self) -> int:
"""
@return the next smallest number
"""
return self.stack.pop(0)
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return len(self.stack) != 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
__________________________________________________________________________________________________