-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.go
117 lines (102 loc) · 1.8 KB
/
bst.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
package main
import (
"fmt"
)
type Node struct {
Value int
Left *Node
Right *Node
}
type Tree struct {
Root *Node
}
func (t *Tree) Insert(value int) {
// First insert, set root.
if t.Root == nil {
t.Root = &Node{Value: value}
} else {
t.Root.Insert(value)
}
}
func (t *Tree) Print() {
t.Root.PrintTree()
}
func (t *Tree) Find(value int) bool {
return t.Root.Find(value)
}
func (n *Node) Insert(value int) {
// Duplicates are no-op.
switch {
case value < n.Value:
// At left leaf, create new child.
if n.Left == nil {
n.Left = &Node{Value: value}
} else {
// Recurse left subtree.
n.Left.Insert(value)
}
case value > n.Value:
// At right leaf, create new child.
if n.Right == nil {
n.Right = &Node{Value: value}
} else {
// Recurse right subtree.
n.Right.Insert(value)
}
}
}
// Print the tree in order
func (n *Node) PrintTree() {
if n.Left != nil {
n.Left.PrintTree()
}
fmt.Println(n.Value)
if n.Right != nil {
n.Right.PrintTree()
}
}
func (n *Node) Find(value int) bool {
if n.Value > value {
if n.Left == nil {
return false
} else {
return n.Left.Find(value)
}
} else if n.Value < value {
if n.Right == nil {
return false
} else {
return n.Right.Find(value)
}
}
return true
}
func (n *Node) Height() int {
var left, right int = 0, 0
if n.Left != nil {
left = n.Left.Height()
}
if n.Right != nil {
right = n.Right.Height()
}
return 1 + maxInt(left, right)
}
func maxInt(a int, b int) int {
if a >= b {
return a
}
return b
}
func main() {
t := Tree{}
t.Insert(7)
t.Insert(1)
t.Insert(14)
t.Insert(4)
t.Insert(9)
t.Insert(2)
t.Insert(0)
t.Print()
fmt.Println(t.Find(4))
fmt.Println(t.Root.Height())
}