C++
Java
Python
Python3
C
C#
JavaScript
Ruby
Swift
Go
Scala
Kotlin
Rust
PHP
TypeScript
Racket
Erlang
Elixir
Dart
monokai
ambiance
chaos
chrome
cloud9_day
cloud9_night
cloud9_night_low_color
clouds
clouds_midnight
cobalt
crimson_editor
dawn
dracula
dreamweaver
eclipse
github
github_dark
gob
gruvbox
gruvbox_dark_hard
gruvbox_light_hard
idle_fingers
iplastic
katzenmilch
kr_theme
kuroir
merbivore
merbivore_soft
mono_industrial
nord_dark
one_dark
pastel_on_dark
solarized_dark
solarized_light
sqlserver
terminal
textmate
tomorrow
tomorrow_night
tomorrow_night_blue
tomorrow_night_bright
tomorrow_night_eighties
twilight
vibrant_ink
xcode
上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
}
};
运行代码
提交
golang 解法, 执行用时: 8 ms, 内存消耗: 6.2 MB, 提交时间: 2022-11-18 09:46:43
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findFrequentTreeSum(root *TreeNode) (ans []int) {
cnt := map[int]int{}
maxCnt := 0
var dfs func(*TreeNode) int
dfs = func(node *TreeNode) int {
if node == nil {
return 0
}
sum := node.Val + dfs(node.Left) + dfs(node.Right)
cnt[sum]++
if cnt[sum] > maxCnt {
maxCnt = cnt[sum]
}
return sum
}
dfs(root)
for s, c := range cnt {
if c == maxCnt {
ans = append(ans, s)
}
}
return
}
python3 解法, 执行用时: 52 ms, 内存消耗: 18.6 MB, 提交时间: 2022-11-18 09:46:31
# 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
'''
我们可以从根结点出发,深度优先搜索这棵二叉树。对于每棵子树,
其子树元素和等于子树根结点的元素值,加上左子树的元素和,以及右子树的元素和。
用哈希表统计每棵子树的元素和的出现次数,计算出现次数的最大值 maxCnt,
最后将出现次数等于 maxCnt 的所有元素和返回。
'''
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
cnt = Counter()
def dfs(node: TreeNode) -> int:
if node is None: return 0
sum = node.val + dfs(node.left) + dfs(node.right)
cnt[sum] += 1
return sum
dfs(root)
maxCnt = max(cnt.values())
return [s for s, c in cnt.items() if c == maxCnt]