From df52a98d0ccf57d63414f4e6ed6ac95faab11dd1 Mon Sep 17 00:00:00 2001 From: Vasko Zdravevski Date: Thu, 7 Mar 2019 21:21:43 -0700 Subject: [PATCH 1/2] day 196: most frequent subtree sum --- day196/problem.go | 33 +++++++++++++++++++++++++++++++++ day196/problem_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 day196/problem.go create mode 100644 day196/problem_test.go diff --git a/day196/problem.go b/day196/problem.go new file mode 100644 index 0000000..a133884 --- /dev/null +++ b/day196/problem.go @@ -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 +} diff --git a/day196/problem_test.go b/day196/problem_test.go new file mode 100644 index 0000000..0a172c8 --- /dev/null +++ b/day196/problem_test.go @@ -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) + } + } +} From 95a1df1ff24a5cfc8747aa57b32a1f48f51aaa03 Mon Sep 17 00:00:00 2001 From: Vasko Zdravevski Date: Thu, 7 Mar 2019 21:22:22 -0700 Subject: [PATCH 2/2] add day 196 to readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index bc1a636..5ceabd7 100644 --- a/README.md +++ b/README.md @@ -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)