Repository: vaskoz/dailycodingproblem-go (go)

Issue:
Day 196
Good morning! Here's your coding interview problem for today.

This problem was asked by Apple.

Given the root of a binary tree, find the most frequent subtree sum. The subtree sum of a node is the sum of all values under a node, including the node itself.

For example, given the following tree:
```
  5
 / \
2  -5
```
Return `2` as it occurs twice: once as the left leaf, and once as the sum of `2 + 5 - 5`.

Pull request description:
Day196
Resolves #404.

Patch:
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)
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
+}


Test patch:
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)
+		}
+	}
+}