@@ -16,42 +16,36 @@ type TreeNode = kit.TreeNode
16
16
17
17
// BSTIterator is the iterator of BST
18
18
type BSTIterator struct {
19
- index int
20
- nums []int
19
+ stack []* TreeNode
21
20
}
22
21
23
22
// Constructor returns a BST iterator
24
23
func Constructor (root * TreeNode ) BSTIterator {
25
- nums := convert (root )
26
- return BSTIterator {
27
- index : 0 ,
28
- nums : nums ,
24
+ stack := make ([]* TreeNode , 0 , 128 )
25
+ res := BSTIterator {
26
+ stack : stack ,
29
27
}
28
+ res .push (root )
29
+ return res
30
30
}
31
31
32
32
// Next returns the next smallest number
33
33
func (it * BSTIterator ) Next () int {
34
- res := it .nums [it .index ]
35
- it .index ++
36
- return res
34
+ size := len (it .stack )
35
+ var top * TreeNode
36
+ it .stack , top = it .stack [:size - 1 ], it .stack [size - 1 ]
37
+ it .push (top .Right )
38
+ return top .Val
37
39
}
38
40
39
41
// HasNext returns whether we have a next smallest number
40
42
func (it * BSTIterator ) HasNext () bool {
41
- return it .index < len (it .nums )
42
- }
43
-
44
- func convert (root * TreeNode ) []int {
45
- res := make ([]int , 0 , 128 )
46
- helper (root , & res )
47
- return res
43
+ return len (it .stack ) > 0
48
44
}
49
45
50
- func helper (root * TreeNode , res * []int ) {
51
- if root == nil {
52
- return
46
+ func (it * BSTIterator ) push (root * TreeNode ) {
47
+ for root != nil {
48
+ it .stack = append (it .stack , root )
49
+ root = root .Left
53
50
}
54
- helper (root .Left , res )
55
- * res = append (* res , root .Val )
56
- helper (root .Right , res )
57
51
}
0 commit comments