Skip to content

Commit

Permalink
Merge pull request #244 from vaskoz/day115
Browse files Browse the repository at this point in the history
Day115
  • Loading branch information
vaskoz committed Dec 16, 2018
2 parents c6cbf9a + 84afe24 commit aac1c03
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,5 @@ problems from
* [Day 112](https://github.com/vaskoz/dailycodingproblem-go/issues/235)
* [Day 113](https://github.com/vaskoz/dailycodingproblem-go/issues/236)
* [Day 114](https://github.com/vaskoz/dailycodingproblem-go/issues/237)
* [Day 115](https://github.com/vaskoz/dailycodingproblem-go/issues/238)
* [Day 116](https://github.com/vaskoz/dailycodingproblem-go/issues/242)
24 changes: 24 additions & 0 deletions day115/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package day115

// IntBinaryTree is a binary tree of integers.
type IntBinaryTree struct {
Value int
Left, Right *IntBinaryTree
}

// SameTreeSubstructure returns true if 't' exists somewhere inside of 's'.
func SameTreeSubstructure(t, s *IntBinaryTree) bool {
if s == nil {
return false
}
return equalTrees(t, s) || SameTreeSubstructure(t, s.Left) || SameTreeSubstructure(t, s.Right)
}

func equalTrees(one, two *IntBinaryTree) bool {
if one == nil && two == nil {
return true
} else if (one == nil && two != nil) || (one != nil && two == nil) || (one.Value != two.Value) {
return false
}
return equalTrees(one.Left, two.Left) || equalTrees(one.Right, two.Right)
}
47 changes: 47 additions & 0 deletions day115/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package day115

import "testing"

var testcases = []struct {
t, s *IntBinaryTree
expected bool
}{
{&IntBinaryTree{
10,
&IntBinaryTree{15, nil, nil},
&IntBinaryTree{20, nil, nil}},
&IntBinaryTree{15,
&IntBinaryTree{10,
&IntBinaryTree{15, nil, nil},
&IntBinaryTree{20, nil, nil}},
&IntBinaryTree{20, nil, nil}},
true},
{&IntBinaryTree{
10, nil, nil},
&IntBinaryTree{15,
&IntBinaryTree{25,
&IntBinaryTree{15, nil, nil},
&IntBinaryTree{20, nil, nil}},
&IntBinaryTree{20, nil, nil}},
false},
{&IntBinaryTree{10, nil, nil},
&IntBinaryTree{15, nil, nil},
false},
}

func TestSameTreeSubstructure(t *testing.T) {
t.Parallel()
for tcid, tc := range testcases {
if result := SameTreeSubstructure(tc.t, tc.s); result != tc.expected {
t.Errorf("TCID%d expected %v got %v", tcid, tc.expected, result)
}
}
}

func BenchmarkSameTreeSubstructure(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
SameTreeSubstructure(tc.t, tc.s)
}
}
}

0 comments on commit aac1c03

Please sign in to comment.