数据结构之实现二叉树的前中后序遍历

学习极客时间《数据结构与算法之美》二叉树章节,用 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
package main

import "fmt"

type tree struct {
value int
left *tree
right *tree
}

func main() {
t := &tree{
1,
&tree{
2,
&tree{
4,
nil,
nil,
},
&tree{
5,
nil,
nil,
},
},
&tree{
3,
&tree{
6,
nil,
nil,
},
nil,
},
}
preOrder(t)
fmt.Println()
inOrder(t)
fmt.Println()
postOrder(t)
fmt.Println()
}

// 前序遍历
func preOrder(t *tree) {
if t == nil {
return
}
fmt.Printf("%d ", t.value)
preOrder(t.left)
preOrder(t.right)
}

// 中序遍历
func inOrder(t *tree) {
if t == nil {
return
}
inOrder(t.left)
fmt.Printf("%d ", t.value)
inOrder(t.right)
}

// 后序遍历
func postOrder(t *tree) {
if t == nil {
return
}
postOrder(t.left)
postOrder(t.right)
fmt.Printf("%d ", t.value)
}

// 1 2 4 5 3 6
// 4 2 5 1 6 3
// 4 5 2 6 3 1
◀        
        ▶