-
Notifications
You must be signed in to change notification settings - Fork 1
/
traversal.go
141 lines (132 loc) · 2.75 KB
/
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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package traversal
import (
"github.com/NewbMiao/algorithm-go/kit/btree"
"github.com/NewbMiao/algorithm-go/kit/stack"
)
// 先序遍历:根,左,右.
func PreOrderRecur(bt *btree.Node) (res []int) {
if bt == nil {
return
}
res = append(res, bt.Value)
res = append(res, PreOrderRecur(bt.Left)...)
res = append(res, PreOrderRecur(bt.Right)...)
return
}
// 中序遍历:左,根,右.
func InOrderRecur(bt *btree.Node) (res []int) {
if bt == nil {
return
}
res = append(res, InOrderRecur(bt.Left)...)
res = append(res, bt.Value)
res = append(res, InOrderRecur(bt.Right)...)
return
}
// 后序遍历:左,右,根.
func LastOrderRecur(bt *btree.Node) (res []int) {
if bt == nil {
return
}
res = append(res, LastOrderRecur(bt.Left)...)
res = append(res, LastOrderRecur(bt.Right)...)
res = append(res, bt.Value)
return
}
func PreOrder(bt *btree.Node) (res []int) {
if bt == nil {
return
}
s := &stack.S{}
s.Push(bt)
for !s.IsEmpty() {
tmp, _ := s.Pop()
cur := tmp.(*btree.Node)
res = append(res, cur.Value)
if cur.Right != nil {
s.Push(cur.Right)
}
if cur.Left != nil {
s.Push(cur.Left)
}
}
return
}
func InOrder(bt *btree.Node) (res []int) {
if bt == nil {
return
}
s := &stack.S{}
cur := bt
for !s.IsEmpty() || cur != nil {
if cur != nil {
// 添加二叉树左边界
s.Push(cur)
cur = cur.Left
} else {
// 左节点为空,切到当前节点的右节点
tmp, ok := s.Pop()
if !ok {
return
}
node := tmp.(*btree.Node)
res = append(res, node.Value)
cur = node.Right
}
}
return
}
func LastOrder1(bt *btree.Node) (res []int) {
if bt == nil {
return
}
s1 := &stack.S{} // 记录 根 左右 入栈, 根 右左 出栈顺序
s2 := &stack.S{} // 逆序s1, 根右左 入栈,记录 左右根 出栈顺序
s1.Push(bt)
for !s1.IsEmpty() {
if tmp, ok := s1.Pop(); ok {
node := tmp.(*btree.Node)
s2.Push(node.Value)
if node.Left != nil {
s1.Push(node.Left)
}
if node.Right != nil {
s1.Push(node.Right)
}
}
}
for !s2.IsEmpty() {
tmp, _ := s2.Pop()
res = append(res, tmp.(int))
}
return
}
func LastOrder2(bt *btree.Node) (res []int) {
if bt == nil {
return
}
var history *btree.Node // 最近一次弹出并打印节点
var cur *btree.Node // 当前栈顶节点
s := &stack.S{}
s.Push(bt)
history = bt // history为nil会影响最左节点的添加
for !s.IsEmpty() {
cur = s.Peek().(*btree.Node)
if cur == nil {
return
}
if cur.Left != nil && cur.Left != history && cur.Right != history {
// 左子树未处理
s.Push(cur.Left)
} else if cur.Right != nil && cur.Right != history {
// 右子树未处理
s.Push(cur.Right)
} else {
// 都处理过
s.Pop()
history = cur
res = append(res, history.Value)
}
}
return
}