Created
June 19, 2022 11:25
-
-
Save shao-wang-me/2ec2ae0d9c59286bdd5144b3bc872f34 to your computer and use it in GitHub Desktop.
LeetCode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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