-
Notifications
You must be signed in to change notification settings - Fork 0
/
btree.go
84 lines (67 loc) · 1.11 KB
/
btree.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
package main
import "fmt"
//import "fmt"
type Node struct {
data int
left *Node
right *Node
}
type Btree struct {
btree *Node
}
type iftree interface{
Insert(num int)
//delete(int num)
show()
}
func (d * Node) init (num int) *Node {
d.left = nil
d.right = nil
d.data = num
return d
}
func Newnodes(num int) *Node {
return new(Node).init(num)
}
func NewTree() *Btree {
return new(Btree).init()
}
func (d* Btree) init() *Btree {
d.btree = nil
return d
}
func (d * Node)Insert (num int) (*Node) {
if d == nil {
return Newnodes(num)
}
if num < d.data {
if d.left == nil {
d.left = Newnodes(num)
return d
} else {
return d.left.Insert(num)
}
} else if (num > d.data){
if d.right == nil {
d.right = Newnodes(num)
return d
} else {
return d.right.Insert(num)
}
}
return d
}
func showInOrder(root *Node) {
if (root != nil) {
showInOrder(root.left)
fmt.Println(root.data)
showInOrder(root.right)
}
}
func main() {
tree := NewTree()
tree.btree = tree.btree.Insert(5)
tree.btree.Insert(7)
tree.btree.Insert(2)
showInOrder(tree.btree)
}