-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (60 loc) · 1.22 KB
/
main.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
package main
type BinaryTree[T int | float32] struct {
Value T
Left *BinaryTree[T]
Right *BinaryTree[T]
}
func insert[T int | float32](node *BinaryTree[T], val T) *BinaryTree[T] {
if node == nil {
return &BinaryTree[T]{
Value: val,
}
}
if val > node.Value {
node.Right = insert[T](node.Right, val)
}
if val < node.Value {
node.Left = insert[T](node.Left, val)
}
return node
}
func makeBtree[T int | float32](mp []T) *BinaryTree[T] {
var node *BinaryTree[T]
for _, v := range mp {
node = insert[T](node, v)
}
return node
}
func inOrder[T int | float32](btree *BinaryTree[T]) {
if btree == nil {
return
}
inOrder[T](btree.Left)
println(btree.Value)
inOrder[T](btree.Right)
}
func postOrder[T int | float32](btree *BinaryTree[T]) {
if btree == nil {
return
}
postOrder[T](btree.Left)
postOrder[T](btree.Right)
println(btree.Value)
}
func preOrder[T int | float32](btree *BinaryTree[T]) {
if btree == nil {
return
}
println(btree.Value)
preOrder[T](btree.Left)
preOrder[T](btree.Right)
}
func main() {
btree := makeBtree[int]([]int{3, 6, 7, 10, 2, 1, 4})
println("Inorder:")
inOrder[int](btree)
println("Post order:")
postOrder[int](btree)
println("Pre order:")
preOrder[int](btree)
}