-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree.go
144 lines (109 loc) · 1.95 KB
/
binary-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
139
140
141
142
143
144
package main
import (
"fmt"
)
type Tree struct {
Left *Tree
Value int
Right *Tree
}
func (t *Tree) Insert(v int) *Tree {
if t == nil {
return &Tree{nil, v, nil}
}
if v < t.Value {
t.Left = t.Left.Insert(v)
return t.Left
}
t.Right = t.Right.Insert(v)
return t.Right
}
// Depth first in-order traversal
func (t *Tree) Traverse(ch chan int) {
if t == nil {
return
}
t.Left.Traverse(ch)
ch <- t.Value
t.Right.Traverse(ch)
}
func (t *Tree) Search(x int) *Tree {
if t == nil {
return nil
}
if t.Value == x {
return t
}
if x < t.Value {
return t.Left.Search(x)
}
return t.Right.Search(x)
}
// Post-order traversal to calculate tree depth
func (t *Tree) Depth() int {
if t == nil {
return 0
}
var left,right int
left = t.Left.Depth()
right = t.Right.Depth()
if left > right {
return left + 1
}
return right + 1
}
func (t *Tree) Min() *Tree {
var min *Tree
if t == nil {
return nil
}
min = t
for min.Left != nil {
min = min.Left
}
return min
}
// Pre-order traversal for graphviz
func (t *Tree) GraphVizAux() {
if(t == nil) {
return
}
if(t.Left != nil) {
fmt.Printf(" %d->%d; \n", t.Value, t.Left.Value)
}
if(t.Right != nil) {
fmt.Printf(" %d->%d; \n", t.Value, t.Right.Value)
}
t.Left.GraphVizAux();
t.Right.GraphVizAux();
}
func (t *Tree) GraphViz() {
fmt.Println("digraph BST {")
fmt.Println("graph [ordering=\"out\"];")
t.GraphVizAux()
fmt.Println("labelloc=\"t\";")
fmt.Printf("label=\"Binary Search Tree with Depth %d\";\n", t.Depth())
fmt.Println("}")
}
func main() {
var t,tmp,tmp2 *Tree
t = t.Insert(2)
t.Insert(1)
tmp = t.Insert(7)
tmp2 = tmp.Insert(4)
tmp = tmp.Insert(8)
tmp2.Insert(3)
tmp = tmp2.Insert(6)
tmp.Insert(5)
/*
ch := make(chan int)
go func() {
t.Traverse(ch)
close(ch)
}()
for i := range ch {
fmt.Println(i)
}
*/
t.GraphViz()
}