-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.go
63 lines (56 loc) · 1.01 KB
/
solution.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
import "fmt"
// TreeNode is a binary tree node
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type stack []*TreeNode
func (stk stack) Push(node *TreeNode) stack {
return append(stk, node)
}
func (stk stack) Pop() (stack, *TreeNode) {
return stk[:len(stk)-1], stk[len(stk)-1]
}
func inorderTraversal(root *TreeNode) []int {
// left, visit, right
var result []int
if root == nil {
return result
}
var stk stack
for {
if root.Left != nil {
stk = stk.Push(root)
root = root.Left
continue
}
result = append(result, root.Val)
if root.Right != nil {
root = root.Right
continue
}
if len(stk) != 0 {
stk, root = stk.Pop()
root.Left = nil
continue
}
break
}
return result
}
func main() {
tree := &TreeNode{1,
&TreeNode{2,
&TreeNode{4,
&TreeNode{7, nil, nil},
nil},
&TreeNode{5, nil, nil}},
&TreeNode{3,
&TreeNode{6,
&TreeNode{8, nil, nil},
&TreeNode{9, nil, nil}},
nil}}
fmt.Printf("%#v", inorderTraversal(tree))
}