-
Notifications
You must be signed in to change notification settings - Fork 0
/
traversal.go
72 lines (55 loc) · 1.69 KB
/
traversal.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
package avltree
import (
"cmp"
)
// VisitFunc is used when traversing the tree. The function will be called with the key and value.
// The traversal can be stopped by returning false.
type VisitFunc[K cmp.Ordered, V any] func(K, V) bool
// InorderTraversal will do an inorder traversal of the whole tree.
func (tree *AVLTree[K, V]) InorderTraversal(visitFunc VisitFunc[K, V]) {
inorderTraversal(tree.root, visitFunc)
}
// PreorderTraversal will do a preorder traversal of the whole tree.
func (tree *AVLTree[K, V]) PreorderTraversal(visitFunc VisitFunc[K, V]) {
preorderTraversal(tree.root, visitFunc)
}
// PostorderTraversal will do a postorder traversal of the whole tree.
func (tree *AVLTree[K, V]) PostorderTraversal(visitFunc VisitFunc[K, V]) {
postorderTraversal(tree.root, visitFunc)
}
func inorderTraversal[K cmp.Ordered, V any](node *Node[K, V], visitFunc VisitFunc[K, V]) bool {
if node == nil {
return true
}
if !inorderTraversal(node.Left, visitFunc) {
return false
}
if !visitFunc(node.Key, node.Value) {
return false
}
return inorderTraversal(node.Right, visitFunc)
}
func preorderTraversal[K cmp.Ordered, V any](node *Node[K, V], visitFunc VisitFunc[K, V]) bool {
if node == nil {
return true
}
if !visitFunc(node.Key, node.Value) {
return false
}
if !preorderTraversal(node.Left, visitFunc) {
return false
}
return preorderTraversal(node.Right, visitFunc)
}
func postorderTraversal[K cmp.Ordered, V any](node *Node[K, V], visitFunc VisitFunc[K, V]) bool {
if node == nil {
return true
}
if !postorderTraversal(node.Left, visitFunc) {
return false
}
if !postorderTraversal(node.Right, visitFunc) {
return false
}
return visitFunc(node.Key, node.Value)
}