-
Notifications
You must be signed in to change notification settings - Fork 0
/
144.go
83 lines (72 loc) · 1.34 KB
/
144.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
73
74
75
76
77
78
79
80
81
82
83
// from 94.go
package main
import (
"fmt"
)
/**
* Definition for a binary tree node.
**/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// https://leetcode.com/problems/binary-tree-inorder-traversal/solutions/127563/binary-tree-inorder-traversal/
/*
func preorderTraversal(root *TreeNode) []int {
var res []int
if root == nil {
return res
}
curr := root
for {
if curr == nil {
break
}
if curr.Left == nil {
res = append(res, curr.Val)
curr = curr.Right
} else {
pre := curr.Left
for {
if pre.Right == nil {
break
}
pre = pre.Right
}
pre.Right = curr
// temp := &TreeNode{curr.Val, curr.Left, curr.Right}
temp := curr
curr = curr.Left
temp.Left = nil
}
}
return res
}
*/
func preorderTraversal_recc(root *TreeNode) []int {
if root == nil {
return []int{}
}
var res []int
res = append(res, root.Val)
if root.Left != nil {
c1 := preorderTraversal_recc(root.Left)
res = append(res, c1...)
}
if root.Right != nil {
c2 := preorderTraversal_recc(root.Right)
res = append(res, c2...)
}
return res
}
func preorderTraversal(root *TreeNode) []int {
return preorderTraversal_recc(root)
}
func main() {
tree1 := &TreeNode{1, nil, nil}
tree2 := &TreeNode{2, nil, nil}
tree := &TreeNode{0, tree1, tree2}
res := preorderTraversal(tree)
fmt.Println(res)
}