-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_structure_tree.go
138 lines (114 loc) · 2.19 KB
/
data_structure_tree.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
package main
import "fmt"
type ElementType string
type BiTreeNode struct {
data ElementType
Lchild *BiTreeNode
Rchild *BiTreeNode
count int
}
type BiTree *BiTreeNode
func createBiTree() *BiTreeNode {
var ch ElementType
fmt.Println("请输入添加的数据:")
fmt.Scan(&ch)
var T BiTree
if ch == "*" {
T = nil
} else {
T = BiTree(new(BiTreeNode))
(*T).data = ch
(*T).Lchild = createBiTree()
(*T).Rchild = createBiTree()
}
return T
}
func preOrderIterate(T BiTree) {
if T == nil {
return
}
fmt.Println(T.data)
preOrderIterate(T.Lchild)
preOrderIterate(T.Rchild)
}
func inOrderIterate(T BiTree) {
if T == nil {
return
}
inOrderIterate(T.Lchild)
fmt.Println(T.data)
inOrderIterate(T.Rchild)
}
func postOrderIterate(T BiTree) {
if T == nil {
return
}
postOrderIterate(T.Lchild)
postOrderIterate(T.Rchild)
fmt.Println(T.data)
}
func NodeNum(T BiTree) int {
if T == nil {
return 0
} else {
return (1 + NodeNum(T.Lchild) + NodeNum(T.Rchild))
}
}
func DepthOfTree(T BiTree) int {
if T == nil {
return 0
} else {
leftDepth := DepthOfTree(T.Lchild)
rightDepth := DepthOfTree(T.Rchild)
if leftDepth > rightDepth {
return leftDepth + 1
} else {
return rightDepth + 1
}
}
}
func LeafNum(T BiTree) int {
if T == nil {
return 0
} else if T.Lchild == nil && T.Rchild == nil {
return 1
} else {
return (LeafNum(T.Lchild) + LeafNum(T.Rchild))
}
}
func findData(T BiTree, data ElementType) BiTree {
if T == nil {
return nil
}
if T.data == data {
return T
} else {
t := findData(T.Lchild, data)
if t != nil {
return t
}
return findData(T.Rchild, data)
}
}
func main() {
t := createBiTree()
fmt.Println("前序遍历:")
preOrderIterate(t)
fmt.Println("中序遍历:")
inOrderIterate(t)
fmt.Println("后序遍历:")
postOrderIterate(t)
fmt.Println("二叉树的节点数量:")
fmt.Println(NodeNum(t))
fmt.Println("二叉树的深度为:")
fmt.Println(DepthOfTree(t))
fmt.Println("二叉树的叶子节点为:")
fmt.Println(LeafNum(t))
fmt.Println("查找二叉树")
dataNode := findData(t, ElementType("b"))
if dataNode == nil {
fmt.Println("没有找到节点")
} else {
fmt.Println(dataNode)
}
}