@@ -16,42 +16,36 @@ type TreeNode = kit.TreeNode
1616
1717// BSTIterator is the iterator of BST
1818type BSTIterator struct {
19- index int
20- nums []int
19+ stack []* TreeNode
2120}
2221
2322// Constructor returns a BST iterator
2423func 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 ,
2927 }
28+ res .push (root )
29+ return res
3030}
3131
3232// Next returns the next smallest number
3333func (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
3739}
3840
3941// HasNext returns whether we have a next smallest number
4042func (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
4844}
4945
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
5350 }
54- helper (root .Left , res )
55- * res = append (* res , root .Val )
56- helper (root .Right , res )
5751}
0 commit comments