#508
Most Frequent Subtree Sum
MediumHash TableTreeDepth-First SearchBinary TreeHash MapDepth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single traversal of the tree to calculate subtree sums and their frequencies. This is efficient because it avoids redundant calculations by leveraging depth-first search.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dictionary to count subtree sums and a variable to track the maximum frequency.
- 2Step 2: Perform a depth-first search to calculate subtree sums for each node while updating the frequency count.
- 3Step 3: After the traversal, identify the sums with the maximum frequency and return them.
solution.py27 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8from collections import defaultdict
9
10def findFrequentTreeSum(root):
11 if not root:
12 return []
13
14 sum_count = defaultdict(int)
15 max_freq = 0
16
17 def subtree_sum(node):
18 nonlocal max_freq
19 if not node:
20 return 0
21 total = node.val + subtree_sum(node.left) + subtree_sum(node.right)
22 sum_count[total] += 1
23 max_freq = max(max_freq, sum_count[total])
24 return total
25
26 subtree_sum(root)
27 return [s for s, freq in sum_count.items() if freq == max_freq]ℹ
Complexity note: The time complexity is O(n) because we traverse each node exactly once. The space complexity is O(n) due to the storage of subtree sums in the dictionary.
- 1Subtree sums can be efficiently calculated using depth-first search.
- 2Using a hash map allows for quick frequency counting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.