[LeetCode] 508. Most Frequent Subtree Sum
508. Most Frequent Subtree Sum
Given the root of a tree, you are asked to find the most frequent subtree sum.
The subtree sum of a node is defined as the sum of all the node values formed
by the subtree rooted at that node (including the node itself).
So what is the most frequent subtree sum value? If there is a tie,
return all the values with the highest frequency in any order.
The subtree sum of a node is defined as the sum of all the node values formed
by the subtree rooted at that node (including the node itself).
So what is the most frequent subtree sum value? If there is a tie,
return all the values with the highest frequency in any order.
Examples 1
Input:
Input:
5 / \ 2 -3return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
Input:
5 / \ 2 -5return [2], since 2 happens twice, however -5 only occur once.
Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.
Subscribe to see which companies asked this question.
找出子樹 加總 最高的
line 10 - 17: 深度優先左右子樹並加總 存到一個 字典叫 self.temp
line 15 - 16: 處理 key error
line 21 - 24: 找出最高的次數
line 25 - 28: 如果出現最高次數 的加總 有多個 就全部 return
留言
張貼留言