Skip to content

Commit

Permalink
Merge pull request #407 from vaskoz/day196
Browse files Browse the repository at this point in the history
Day196
  • Loading branch information
vaskoz committed Mar 8, 2019
2 parents b3ff7d8 + 95a1df1 commit 088ac0d
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,4 +205,5 @@ problems from
* [Day 192](https://github.com/vaskoz/dailycodingproblem-go/issues/397)
* [Day 194](https://github.com/vaskoz/dailycodingproblem-go/issues/400)
* [Day 195](https://github.com/vaskoz/dailycodingproblem-go/issues/401)
* [Day 196](https://github.com/vaskoz/dailycodingproblem-go/issues/404)
* [Day 197](https://github.com/vaskoz/dailycodingproblem-go/issues/405)
33 changes: 33 additions & 0 deletions day196/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day196

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

// MostFrequentSubtreeSum returns the most frequent subtree sum.
// Runs in linear time.
func MostFrequentSubtreeSum(head *BinaryTree) int {
freq := make(map[int]int)
subtreeFreqCount(head, freq)
var result, mostFreq int
for sum, count := range freq {
if count > mostFreq {
mostFreq = count
result = sum
}
}
return result
}

func subtreeFreqCount(head *BinaryTree, freq map[int]int) int {
if head == nil {
return 0
}
left := subtreeFreqCount(head.Left, freq)
right := subtreeFreqCount(head.Right, freq)
sum := left + right + head.Value
freq[sum]++
return sum
}
31 changes: 31 additions & 0 deletions day196/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package day196

import "testing"

var testcases = []struct {
head *BinaryTree
expected int
}{
{&BinaryTree{
5,
&BinaryTree{2, nil, nil},
&BinaryTree{-5, nil, nil},
}, 2},
}

func TestMostFrequentSubtreeSum(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := MostFrequentSubtreeSum(tc.head); result != tc.expected {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

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

0 comments on commit 088ac0d

Please sign in to comment.