-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbintree.go
149 lines (125 loc) · 2.34 KB
/
bintree.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
145
146
147
148
149
package ds
type BinaryTree struct {
left *BinaryTree
right *BinaryTree
val interface{}
}
func MakeBinaryTree(val interface{}) *BinaryTree {
var b BinaryTree
return &b
}
func MakeBinaryTreeWithLeftSubtree(valToAdd interface{}, lefty *BinaryTree) *BinaryTree {
var b BinaryTree
b.val = valToAdd
b.left = lefty
return &b
}
func MakeBinaryTreeWithRightSubtree(valToAdd interface{}, righty *BinaryTree) *BinaryTree {
var b BinaryTree
b.val = valToAdd
b.right = righty
return &b
}
func MakeBinaryTreeWithSubtrees(valToAdd interface{}, lefty, righty *BinaryTree) *BinaryTree {
var b BinaryTree
b.val = valToAdd
b.left = lefty
b.right = righty
return &b
}
func (b *BinaryTree) IsLeaf() bool {
return (b.left == nil && b.right == nil)
}
func (b BinaryTree) HasLeftChild() bool {
return b.left != nil
}
func (b BinaryTree) HasRightChild() bool {
return b.right != nil
}
func (b BinaryTree) Depth() int {
var d int
if b.IsLeaf() {
d = 1
} else {
if b.left == nil {
d = (*b.right).Depth() + 1
} else if b.right == nil {
d = (*b.left).Depth() + 1
} else {
ld := b.left.Depth() + 1
rd := b.right.Depth() + 1
if ld > rd {
d = ld
} else {
d = rd
}
}
}
return d
}
func (b *BinaryTree) RemoveLeftSubtree() {
b.left = nil
}
func (b *BinaryTree) RemoveRightSubtree() {
b.right = nil
}
//Dos
func (t *BinaryTree) prefixDo(f func(interface{})) {
f(t.val)
if t.left != nil {
t.left.prefixDo(f)
}
if t.right != nil {
t.right.prefixDo(f)
}
}
func (t *BinaryTree) inOrderDo(f func(interface{})) {
if t.left != nil {
t.left.inOrderDo(f)
}
f(t.val)
if t.right != nil {
t.right.inOrderDo(f)
}
}
func (t *BinaryTree) postfixDo(f func(interface{})) {
if t.left != nil {
t.left.postfixDo(f)
}
if t.right != nil {
t.right.postfixDo(f)
}
f(t.val)
}
func (t *BinaryTree) breadthFirstDo(f func(interface{})) {
q := MakeQueue()
q.Push(&t)
for !q.Empty() {
p := q.Front().(*BinaryTree)
q.Pop()
f(p.val)
//Enque Child nodes
if p.HasLeftChild() {
q.Push(p.left)
}
if p.HasRightChild() {
q.Push(p.right)
}
}
}
func (t *BinaryTree) depthFirstDo(f func(interface{})) {
s := MakeStack()
s.Push(&t)
for !s.Empty() {
p := s.Top().(*BinaryTree)
s.Pop()
f(p.val)
//Enque Child nodes
if p.HasLeftChild() {
s.Push(p.left)
}
if p.HasRightChild() {
s.Push(p.right)
}
}
}