Skip to content

Commit ec56ddb

Browse files
committed
add leetcode 173
1 parent 7442740 commit ec56ddb

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package leetcode
2+
3+
import . "github.com/lijinglin2019/algorithm-go/leetcode/common"
4+
5+
type BSTIterator struct {
6+
stack []*TreeNode
7+
length int
8+
}
9+
10+
func Constructor(root *TreeNode) BSTIterator {
11+
if root == nil {
12+
return BSTIterator{}
13+
}
14+
15+
stack := []*TreeNode{root}
16+
n := root
17+
for n.Left != nil {
18+
stack = append(stack, n.Left)
19+
n = n.Left
20+
}
21+
22+
return BSTIterator{
23+
stack: stack,
24+
length: len(stack),
25+
}
26+
}
27+
28+
/** @return the next smallest number */
29+
func (this *BSTIterator) Next() int {
30+
n := this.stack[this.length-1]
31+
this.stack = this.stack[:this.length-1]
32+
33+
tmp := n.Right
34+
for tmp != nil {
35+
this.stack = append(this.stack, tmp)
36+
tmp = tmp.Left
37+
}
38+
this.length = len(this.stack)
39+
40+
return n.Val
41+
}
42+
43+
/** @return whether we have a next smallest number */
44+
func (this *BSTIterator) HasNext() bool {
45+
if this.length != 0 {
46+
return true
47+
}
48+
return false
49+
}
50+
51+
/**
52+
* Your BSTIterator object will be instantiated and called as such:
53+
* obj := Constructor(root);
54+
* param_1 := obj.Next();
55+
* param_2 := obj.HasNext();
56+
*/
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package leetcode
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
8+
. "github.com/lijinglin2019/algorithm-go/leetcode/common"
9+
)
10+
11+
func TestConstructor(t *testing.T) {
12+
assert.Equal(t, BSTIterator{}, Constructor((*TreeNode)(nil)))
13+
assert.Equal(t, BSTIterator{stack: []*TreeNode{{}}, length: 1}, Constructor(&TreeNode{}))
14+
15+
constructor := Constructor(TreeNodeDecoder("[7, 3, 15, null, null, 9, 20]"))
16+
for _, v := range []int{3, 7, 9, 15, 20} {
17+
assert.Equal(t, true, constructor.HasNext())
18+
assert.Equal(t, v, constructor.Next())
19+
}
20+
assert.Equal(t, false, constructor.HasNext())
21+
}

0 commit comments

Comments
 (0)