-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree.go
48 lines (42 loc) · 865 Bytes
/
binary_tree.go
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
func kthSmallest(root *TreeNode, k int) int {
t := Constructor(root)
c := 0
for t.HasNext() {
c++
v := t.Next()
if k == c {
return v
}
}
return -1
}
type BSTIterator struct {
stack []*TreeNode
}
func Constructor(root *TreeNode) BSTIterator {
st := []*TreeNode{}
cur := root
for cur != nil {
st = append(st, cur)
cur = cur.Left
}
return BSTIterator{
stack: st,
}
}
/** @return the next smallest number */
func (this *BSTIterator) Next() int {
cur := this.stack[len(this.stack)-1]
this.stack = this.stack[:len(this.stack)-1]
ret := cur.Val
cur = cur.Right
for cur != nil {
this.stack = append(this.stack, cur)
cur = cur.Left
}
return ret
}
/** @return whether we have a next smallest number */
func (this *BSTIterator) HasNext() bool {
return len(this.stack) > 0
}