-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #407 from vaskoz/day196
Day196
- Loading branch information
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |