Skip to content

Commit

Permalink
Merge 33a7f7e into e56d2e1
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Apr 17, 2019
2 parents e56d2e1 + 33a7f7e commit d3d97c6
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,4 @@ problems from
* [Day 234](https://github.com/vaskoz/dailycodingproblem-go/issues/481)
* [Day 235](https://github.com/vaskoz/dailycodingproblem-go/issues/483)
* [Day 236](https://github.com/vaskoz/dailycodingproblem-go/issues/485)
* [Day 237](https://github.com/vaskoz/dailycodingproblem-go/issues/487)
31 changes: 31 additions & 0 deletions day237/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Package day237 has a note.
// NOTE: I didn't provide an API for a k-ary
// tree. It's up to the user to build a valid
// k-ary tree.
package day237

// KaryTree is a k-ary tree of integers.
type KaryTree struct {
Value int
Children []*KaryTree
}

// IsTreeSymmetric answers if its data and shape remain
// unchanged when it is reflected about the root node.
func IsTreeSymmetric(tree *KaryTree) bool {
return equal(tree, tree)
}

func equal(a, b *KaryTree) bool {
if a == nil && b == nil {
return true
} else if a != nil && b != nil && a.Value == b.Value {
for i := range a.Children {
if !equal(a.Children[i], b.Children[len(a.Children)-1-i]) {
return false
}
}
return true
}
return false
}
61 changes: 61 additions & 0 deletions day237/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package day237

import "testing"

var testcases = []struct {
root *KaryTree
symmetric bool
}{
{&KaryTree{
4,
[]*KaryTree{
{
3,
[]*KaryTree{{9, nil}, nil, nil},
},
{
5,
[]*KaryTree{nil, nil, nil},
},
{
3,
[]*KaryTree{nil, nil, {9, nil}},
},
},
}, true},
{nil, true},
{&KaryTree{
4,
[]*KaryTree{
{
3,
[]*KaryTree{nil, {9, nil}, nil},
},
{
5,
[]*KaryTree{nil, nil, nil},
},
{
3,
[]*KaryTree{nil, nil, {9, nil}},
},
},
}, false},
}

func TestIsTreeSymmetric(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := IsTreeSymmetric(tc.root); result != tc.symmetric {
t.Errorf("Expected %v, got %v", tc.symmetric, result)
}
}
}

func BenchmarkIsTreeSymmetric(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
IsTreeSymmetric(tc.root)
}
}
}

0 comments on commit d3d97c6

Please sign in to comment.