Skip to content

Instantly share code, notes, and snippets.

@shao-wang-me
Created June 19, 2022 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shao-wang-me/2ec2ae0d9c59286bdd5144b3bc872f34 to your computer and use it in GitHub Desktop.
Save shao-wang-me/2ec2ae0d9c59286bdd5144b3bc872f34 to your computer and use it in GitHub Desktop.
LeetCode
# 508. Most Frequent Subtree Sum
# https://leetcode.com/problems/most-frequent-subtree-sum/
# Easy
# 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: TreeNode) -> List[int]:
def dfs(root):
if not root:
return 0
nonlocal max_freq
this_sum = dfs(root.left) + dfs(root.right) + root.val
if this_sum not in sum_freqs:
sum_freqs[this_sum] = 1
else:
sum_freqs[this_sum] += 1
if sum_freqs[this_sum] == max_freq:
ans.append(this_sum)
elif sum_freqs[this_sum] > max_freq:
max_freq += 1
ans.clear()
ans.append(this_sum)
return this_sum
sum_freqs = {}
max_freq = 0
ans = []
dfs(root)
return ans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment