-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathBinaryTree.go
More file actions
85 lines (76 loc) · 1.87 KB
/
BinaryTree.go
File metadata and controls
85 lines (76 loc) · 1.87 KB
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
package BinaryTree
import "cmp"
type Node[T cmp.Ordered] struct {
data T
parent *Node[T]
left *Node[T]
right *Node[T]
}
type BinaryTree[T cmp.Ordered] struct {
root *Node[T]
}
func (tree *BinaryTree[T]) InsertItem(i T) {
if tree.root == nil {
tree.root = &Node[T]{data: i}
return
}
currentNode := tree.root
for {
if i > currentNode.data {
if currentNode.right == nil {
currentNode.right = &Node[T]{data: i, parent: currentNode}
return
}
currentNode = currentNode.right
} else {
if currentNode.left == nil {
currentNode.left = &Node[T]{data: i, parent: currentNode}
return
}
currentNode = currentNode.left
}
}
}
func (tree *BinaryTree[T]) SearchItem(i T) (*Node[T], bool) {
if tree.root == nil {
return nil, false
}
currentNode := tree.root
for currentNode != nil {
if cmp.Compare(i, currentNode.data) == 0 {
return currentNode, true
} else if cmp.Compare(i, currentNode.data) == 1 {
currentNode = currentNode.right
} else if cmp.Compare(i, currentNode.data) == -1 {
currentNode = currentNode.left
}
}
return nil, false
}
func (tree *BinaryTree[T]) InorderTraversal(subtree *Node[T], callback func(T)) {
if subtree.left != nil {
tree.InorderTraversal(subtree.left, callback)
}
callback(subtree.data)
if subtree.right != nil {
tree.InorderTraversal(subtree.right, callback)
}
}
func (tree *BinaryTree[T]) PreorderTraversal(subtree *Node[T], callback func(T)) {
callback(subtree.data)
if subtree.left != nil {
tree.PreorderTraversal(subtree.left, callback)
}
if subtree.right != nil {
tree.PreorderTraversal(subtree.right, callback)
}
}
func (tree *BinaryTree[T]) PostorderTraversal(subtree *Node[T], callback func(T)) {
if subtree.left != nil {
tree.PostorderTraversal(subtree.left, callback)
}
if subtree.right != nil {
tree.PostorderTraversal(subtree.right, callback)
}
callback(subtree.data)
}