-
Notifications
You must be signed in to change notification settings - Fork 31
/
problem_test.go
84 lines (77 loc) · 1.59 KB
/
problem_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
74
75
76
77
78
79
80
81
82
83
84
package day179
import "testing"
var testcases = []struct {
postorder []int
expected *BinaryTree
}{
{[]int{2, 4, 3, 8, 7, 5}, &BinaryTree{
5,
&BinaryTree{
3,
&BinaryTree{2, nil, nil},
&BinaryTree{4, nil, nil},
},
&BinaryTree{
7,
nil,
&BinaryTree{8, nil, nil},
},
}},
{[]int{1, 7, 5, 50, 40, 10}, &BinaryTree{
10,
&BinaryTree{
5,
&BinaryTree{1, nil, nil},
&BinaryTree{7, nil, nil},
},
&BinaryTree{
40,
nil,
&BinaryTree{50, nil, nil},
},
}},
{[]int{}, nil},
}
func TestBuildTreeFromPostorder(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if result := BuildTreeFromPostorder(tc.postorder); !equal(result, tc.expected) {
t.Errorf("Trees don't match for tcid%d", tcid)
}
}
}
func BenchmarkBuildTreeFromPostorder(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
BuildTreeFromPostorder(tc.postorder)
}
}
}
func TestBuildTreeFromPostorderLinear(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if result := BuildTreeFromPostorderLinear(tc.postorder); !equal(result, tc.expected) {
t.Errorf("Trees don't match for tcid%d", tcid)
}
}
}
func BenchmarkBuildTreeFromPostorderLinear(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
BuildTreeFromPostorderLinear(tc.postorder)
}
}
}
func equal(a, b *BinaryTree) bool {
switch {
case a == nil && b != nil:
return false
case a != nil && b == nil:
return false
case a == nil && b == nil:
return true
case a.Value != b.Value:
return false
}
return equal(a.Left, b.Left) && equal(a.Right, b.Right)
}