Most Frequent Subtree Sum — LeetCode 508 Python Solution
MediumTreeDepth-First SearchHash TableBinary Tree
- Problem
- #508
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
Example
- Input
- root = [5,2,-3]
- Output
- [2,-3,4]
Python solution
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
s = l + r + root.val
cnt[s] += 1
return s
cnt = Counter()
dfs(root)
mx = max(cnt.values())
return [k for k, v in cnt.items() if v == mx]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 508. Most Frequent Subtree Sum is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
LeetCode 652Find Duplicate SubtreesMediumLeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 863All Nodes Distance K in Binary TreeMediumLeetCode 865Smallest Subtree with all the Deepest NodesMediumLeetCode 987Vertical Order Traversal of a Binary TreeHardLeetCode 1110Delete Nodes And Return ForestMedium
Frequently asked questions
- How hard is LeetCode 508. Most Frequent Subtree Sum?
- LeetCode 508. Most Frequent Subtree Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 508. Most Frequent Subtree Sum?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 508. Most Frequent Subtree Sum?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 508. Most Frequent Subtree Sum cover?
- LeetCode 508. Most Frequent Subtree Sum is tagged Tree, Depth-First Search, Hash Table and Binary Tree on LeetCode.