-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob0173.go
79 lines (65 loc) · 1.1 KB
/
prob0173.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package prob0173
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// --------
type StackNode struct {
Data []*TreeNode
}
func (s *StackNode) Top() *TreeNode {
if len(s.Data) == 0 {
return nil
}
return s.Data[len(s.Data)-1]
}
func (s *StackNode) Push(i *TreeNode) {
s.Data = append(s.Data, i)
}
func (s *StackNode) Pop() {
if len(s.Data) == 0 {
}
s.Data = s.Data[0 : len(s.Data)-1]
}
func (s *StackNode) IsEmpty() bool {
return len(s.Data) == 0
}
func NewStackInt() *StackNode {
return &StackNode{
Data: []*TreeNode{},
}
}
type BSTIterator struct {
S *StackNode
}
func Constructor(root *TreeNode) BSTIterator {
b := BSTIterator{
S: NewStackInt(),
}
cursor := root
for cursor != nil {
b.S.Push(cursor)
cursor = cursor.Left
}
return b
}
func (this *BSTIterator) Next() int {
top := this.S.Top()
if top == nil {
return 0
}
res := top.Val
this.S.Pop()
if top.Right != nil {
cursor := top.Right
for cursor != nil {
this.S.Push(cursor)
cursor = cursor.Left
}
}
return res
}
func (this *BSTIterator) HasNext() bool {
return !this.S.IsEmpty()
}