File tree 1 file changed +19
-17
lines changed
1 file changed +19
-17
lines changed Original file line number Diff line number Diff line change 3
3
4
4
Calling next() will return the next smallest number in the BST.
5
5
6
- Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
7
-
8
- Credits:
9
- Special thanks to @ts for adding this problem and creating all test cases.
6
+ Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
10
7
'''
11
8
12
9
# Definition for a binary tree node
16
13
# self.left = None
17
14
# self.right = None
18
15
16
+ # Definition for a binary tree node
17
+ # class TreeNode(object):
18
+ # def __init__(self, x):
19
+ # self.val = x
20
+ # self.left = None
21
+ # self.right = None
22
+
19
23
class BSTIterator (object ):
20
24
def __init__ (self , root ):
21
25
"""
22
26
:type root: TreeNode
23
27
"""
24
28
self .stack = []
25
- self .cur = root
26
-
29
+ self .push (root )
27
30
31
+ def push (self , node ):
32
+ while node :
33
+ self .stack .append (node )
34
+ node = node .left
35
+
28
36
def hasNext (self ):
29
37
"""
30
38
:rtype: bool
31
39
"""
32
- return self .stack or self . cur
40
+ return len ( self .stack ) > 0
33
41
34
42
def next (self ):
35
43
"""
36
44
:rtype: int
37
45
"""
38
- while self .cur :
39
- self .stack .append (self .cur )
40
- self .cur = self .cur .left
41
-
42
- self .cur = self .stack .pop ()
43
- node = self .cur
44
- self .cur = self .cur .right
45
-
46
- return node .val
47
-
46
+ top = self .stack .pop ()
47
+ self .push (top .right )
48
+ return top .val
49
+
48
50
# Your BSTIterator will be called like this:
49
51
# i, v = BSTIterator(root), []
50
52
# while i.hasNext(): v.append(i.next())
You can’t perform that action at this time.
0 commit comments