-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0094.go
48 lines (40 loc) · 998 Bytes
/
0094.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
package main
func inorderTraversal(root *TreeNode) []int {
//if root == nil {
// return nil
//}
//
//resLeft := append(inorderTraversal(root.Left))
//resLeft = append(resLeft, root.Val)
//var res = append(resLeft, inorderTraversal(root.Right)...)
//return res
return inorderTraversalWithLoop(root)
}
func inorderTraversalWithLoop(root *TreeNode) []int {
var res []int
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return append(res, root.Val)
}
var nodeArray []*TreeNode
nodeArray = append(nodeArray, root)
for len(nodeArray) > 0 {
curNode := nodeArray[len(nodeArray)-1]
if curNode.Left != nil {
nodeArray = append(nodeArray, curNode.Left)
} else {
//中序节点弹出
res = append(res, curNode.Val)
nodeArray = nodeArray[:len(nodeArray)-1]
if len(nodeArray)-1 > -1 {
nodeArray[len(nodeArray)-1].Left = nil
}
if curNode.Right != nil {
nodeArray = append(nodeArray, curNode.Right)
}
}
}
return res
}