-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathredblack_tree_test.go
More file actions
72 lines (55 loc) · 1.29 KB
/
redblack_tree_test.go
File metadata and controls
72 lines (55 loc) · 1.29 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
package algo_test
import (
"github.com/brnstz/algo"
"fmt"
"io"
"math"
"os"
"testing"
)
// Implement NodeValue interface for strings
type stringNode string
func (s stringNode) Less(other_ algo.NodeValue) bool {
other := other_.(stringNode)
return s < other
}
func (s stringNode) Equals(other_ algo.NodeValue) bool {
other := other_.(stringNode)
return s == other
}
func TestRedBlack(t *testing.T) {
tree := algo.RedBlackTree{}
fh, err := os.Open("data/tale.txt")
if err != nil {
t.Fatal(err)
}
defer fh.Close()
var word stringNode
for {
_, err := fmt.Fscan(fh, &word)
if err == io.EOF {
break
}
tree.Put(word)
}
// Tree should have some words but not others
var yesFind, noFind stringNode
yesFind = "goodfellowship"
noFind = "slfkjkldsf"
if tree.Find(yesFind) != true {
t.Fatal("Cannot find word")
}
if tree.Find(noFind) != false {
t.Fatal("Found unexpected word")
}
height := tree.Height()
// A red black tree should have at most 2log(n + 1) height
maxNodes := 2 * math.Log2(float64(tree.Root.NodeCount+1))
if float64(height) > maxNodes {
t.Fatalf("Tree is too high, actual: %v, expected < %v", height, maxNodes)
}
out := tree.BFSString()
fmt.Print(out)
fmt.Println("Tree height: ", tree.Height())
fmt.Println("Node count: ", tree.Root.NodeCount)
}