-
Notifications
You must be signed in to change notification settings - Fork 548
/
TreeNode.go
126 lines (96 loc) · 2.19 KB
/
TreeNode.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package kit
import (
"fmt"
)
// TreeNode is tree's node
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func indexOf(val int, nums []int) int {
for i, v := range nums {
if v == val {
return i
}
}
msg := fmt.Sprintf("%d 不存在于 %v 中", val, nums)
panic(msg)
}
// PreIn2Tree 把 preorder 和 inorder 切片转换成 二叉树
func PreIn2Tree(pre, in []int) *TreeNode {
if len(pre) != len(in) {
panic("preIn2Tree 中两个切片的长度不相等")
}
if len(in) == 0 {
return nil
}
res := &TreeNode{
Val: pre[0],
}
if len(in) == 1 {
return res
}
idx := indexOf(res.Val, in)
res.Left = PreIn2Tree(pre[1:idx+1], in[:idx])
res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:])
return res
}
// InPost2Tree 把 inorder 和 postorder 切片转换成 二叉树
func InPost2Tree(in, post []int) *TreeNode {
if len(post) != len(in) {
panic("inPost2Tree 中两个切片的长度不相等")
}
if len(in) == 0 {
return nil
}
res := &TreeNode{
Val: post[len(post)-1],
}
if len(in) == 1 {
return res
}
idx := indexOf(res.Val, in)
res.Left = InPost2Tree(in[:idx], post[:idx])
res.Right = InPost2Tree(in[idx+1:], post[idx:len(post)-1])
return res
}
// Tree2Preorder 把 二叉树 转换成 preorder 的切片
func Tree2Preorder(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := []int{root.Val}
res = append(res, Tree2Preorder(root.Left)...)
res = append(res, Tree2Preorder(root.Right)...)
return res
}
// Tree2Inorder 把 二叉树转换成 inorder 的切片
func Tree2Inorder(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := Tree2Inorder(root.Left)
res = append(res, root.Val)
res = append(res, Tree2Inorder(root.Right)...)
return res
}
// Tree2Postorder 把 二叉树 转换成 postorder 的切片
func Tree2Postorder(root *TreeNode) []int {
if root == nil {
return nil
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
res := Tree2Postorder(root.Left)
res = append(res, Tree2Postorder(root.Right)...)
res = append(res, root.Val)
return res
}