-
Notifications
You must be signed in to change notification settings - Fork 21
/
BinaryTreeInorderTraversal.go
71 lines (63 loc) 路 1.27 KB
/
BinaryTreeInorderTraversal.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
package BinaryTreeInorderTraversal
//Given a binary tree, return the inorder traversal of its nodes' values.
//
//For example:
//Given binary tree [1,null,2,3],
//1
//\
//2
///
//3
//return [1,3,2].
//
//Note: Recursive solution is trivial, could you do it iteratively?
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
//Accepted.
func inorderTraversal(root *TreeNode) []int {
list := make([]int, 0)
if root == nil {
return list
}
stack := make([]*TreeNode, 0)
for ; root != nil || len(stack) != 0; {
for ; root != nil; {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack)-1]
list = append(list, root.Val)
stack = removeIndex(stack, len(stack)-1)
root = root.Right
}
return list
}
func removeIndex(s []*TreeNode, index int) []*TreeNode {
return append(s[:index], s[index+1:]...)
}
//Recursive solution.
//Accepted.
//func inorderTraversal(root *TreeNode) []int {
// list := make([]int, 0)
//
// if root == nil {
// return list
// }
// if root.Left != nil {
// for _, i := range inorderTraversal(root.Left) {
// list = append(list, i)
// }
// }
//
// list = append(list, root.Val)
//
// if root.Right != nil {
// for _, i := range inorderTraversal(root.Right) {
// list = append(list, i)
// }
// }
// return list
//}