-
Notifications
You must be signed in to change notification settings - Fork 0
/
20190626-173.binary-search-tree-iterator.go
63 lines (56 loc) · 1.3 KB
/
20190626-173.binary-search-tree-iterator.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
package main
/*
* @lc app=leetcode id=173 lang=golang
*
* [173] Binary Search Tree Iterator
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type BSTIterator struct {
stack *Stack173
}
func Constructor(root *TreeNode) BSTIterator {
stack := make(Stack173, 0)
bst := BSTIterator{&stack}
for root != nil {
bst.stack.push(root)
root = root.Left
}
return bst
}
/** @return the next smallest number */
func (this *BSTIterator) Next() int {
node := this.stack.pop()
res := node.Val
node = node.Right
for node != nil {
this.stack.push(node)
node = node.Left
}
return res
}
/** @return whether we have a next smallest number */
func (this *BSTIterator) HasNext() bool {
return !this.stack.isEmpty()
}
/**
* Your BSTIterator object will be instantiated and called as such:
* obj := Constructor(root);
* param_1 := obj.Next();
* param_2 := obj.HasNext();
*/
// Stack173 : a simple stack implementation
type Stack173 []*TreeNode
func (s *Stack173) isEmpty() bool { return len(*s) == 0 }
func (s *Stack173) push(t *TreeNode) { *s = append(*s, t) }
func (s *Stack173) pop() *TreeNode {
res := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return res
}