-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinternal_test.go
67 lines (57 loc) · 1.33 KB
/
internal_test.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
package stree
import (
"cmp"
"math"
"testing"
)
func TestVine(t *testing.T) {
const numElem = 25
// Construct a tree with consecutive integers.
tree := New(100, cmp.Compare[int])
for i := range numElem {
tree.Add(i + 1)
}
// Flatten the tree node into a right-linked vine and verify that the result
// contains the original elements.
hd := treeToVine(tree.root)
t.Run("Collapse", func(t *testing.T) {
i := 0
for cur := hd; cur != nil; cur = cur.right {
i++
if cur.X != i {
t.Errorf("Node value: got %d, want %d", cur.X, i)
}
if cur.left != nil {
t.Errorf("Node %d has a non-nil left pointer: %v", i, cur.left)
}
}
if i != numElem {
t.Errorf("Got %d nodes, want %d", i, numElem)
}
})
// Reconstitute the tree and verify it is balanced and properly ordered.
t.Run("Rebuild", func(t *testing.T) {
rec := vineToTree(hd, numElem)
want := int(math.Ceil(math.Log2(numElem)))
if got := rec.height(); got > want {
t.Errorf("Got height %d, want %d", got, want)
}
i := 0
rec.inorder(func(z int) bool {
i++
if z != i {
t.Errorf("Node value: got %d, want %d", z, i)
}
return true
})
if i != numElem {
t.Errorf("Got %d nodes, want %d", i, numElem)
}
})
}
func (n *node[T]) height() int {
if n == nil {
return 0
}
return max(n.left.height(), n.right.height()) + 1
}