-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path144. Binary Tree Preorder Traversal.go
72 lines (65 loc) · 1.36 KB
/
144. Binary Tree Preorder Traversal.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
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 递归
func preorderTraversal(root *TreeNode) []int {
res := []int{}
if root != nil {
res = append(res, root.Val)
tmp := preorderTraversal(root.Left)
for _, t := range tmp {
res = append(res, t)
}
tmp = preorderTraversal(root.Right)
for _, t := range tmp {
res = append(res, t)
}
}
return res
}
// 解法二 递归
func preorderTraversal1(root *TreeNode) []int {
var result []int
preorder(root, &result)
return result
}
func preorder(root *TreeNode, output *[]int) {
if root != nil {
*output = append(*output, root.Val)
preorder(root.Left, output)
preorder(root.Right, output)
}
}
// 解法三 非递归,用栈模拟递归过程
func preorderTraversal2(root *TreeNode) []int {
if root == nil {
return []int{}
}
stack, res := []*TreeNode{}, []int{}
stack = append(stack, root)
for len(stack) != 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if node != nil {
res = append(res, node.Val)
}
if node.Right != nil {
stack = append(stack, node.Right)
}
if node.Left != nil {
stack = append(stack, node.Left)
}
}
return res
}