-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution508.cs
46 lines (36 loc) · 1.13 KB
/
Solution508.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution508
{
/// <summary>
/// 508. Most Frequent Subtree Sum - Medium
/// <a href="https://leetcode.com/problems/most-frequent-subtree-sum">See the problem</a>
/// </summary>
public int[] FindFrequentTreeSum(TreeNode root)
{
var sumCount = new Dictionary<int, int>();
var maxCount = 0;
Traverse(root, sumCount, ref maxCount);
var result = new List<int>();
foreach (var (sum, count) in sumCount)
{
if (count == maxCount)
{
result.Add(sum);
}
}
return result.ToArray();
}
private int Traverse(TreeNode node, Dictionary<int, int> sumCount, ref int maxCount)
{
if (node == null)
{
return 0;
}
var sum = node.val + Traverse(node.left, sumCount, ref maxCount) + Traverse(node.right, sumCount, ref maxCount);
sumCount[sum] = sumCount.GetValueOrDefault(sum, 0) + 1;
maxCount = Math.Max(maxCount, sumCount[sum]);
return sum;
}
}