-
Notifications
You must be signed in to change notification settings - Fork 97
/
lca_test.go
73 lines (68 loc) · 1.69 KB
/
lca_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
68
69
70
71
72
73
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package btrees
import "testing"
func TestLCA(t *testing.T) {
// A Binary Tree of height 5.
tree := &BTree{"A",
&BTree{"B",
&BTree{"C",
&BTree{"D", nil, nil},
&BTree{"E", nil, nil}},
&BTree{"F",
nil,
&BTree{"G",
&BTree{"H", nil, nil},
nil}}},
&BTree{"I",
&BTree{"J",
nil,
&BTree{"K",
&BTree{"L",
nil,
&BTree{"M", nil, nil}},
&BTree{"N", nil, nil}}},
&BTree{"O",
nil,
&BTree{"P", nil, nil}}}}
for _, test := range []struct {
t, n0, n1 *BTree
want *BTree
}{
{&BTree{"TREE", nil, nil}, nil, nil, nil},
{tree, tree.left, tree.right, tree}, // n0 = B; n1 = I; want = A
{tree, tree.right.left.right.left.right, tree.right.left.right.right, tree.right.left.right}, // n0 = M; n1 = N; want = K
} {
if got := LCA(test.t, test.n0, test.n1); got != test.want {
t.Errorf("LCA(%v, %v, %v) = %v; want %v", test.t, test.n0, test.n1, got, test.want)
}
}
}
func BenchmarkLCA(b *testing.B) {
tree := &BTree{"A",
&BTree{"B",
&BTree{"C",
&BTree{"D", nil, nil},
&BTree{"E", nil, nil}},
&BTree{"F",
nil,
&BTree{"G",
&BTree{"H", nil, nil},
nil}}},
&BTree{"I",
&BTree{"J",
nil,
&BTree{"K",
&BTree{"L",
nil,
&BTree{"M", nil, nil}},
&BTree{"N", nil, nil}}},
&BTree{"O",
nil,
&BTree{"P", nil, nil}}}}
b.ResetTimer()
for i := 0; i < b.N; i++ {
LCA(tree, tree.right.left.right.left.right, tree.right.left.right.right) // n0 = M; n1 = N
}
}