-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[2022-06-19]508. 出现次数最多的子树元素和👋树👋深度优先搜索👋哈希表👋二叉树 #66
Comments
508. 出现次数最多的子树元素和DescriptionDifficulty: 中等 Related Topics: 树, 深度优先搜索, 哈希表, 二叉树 给你一个二叉树的根结点 一个结点的 「子树元素和」 定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。 示例 1:
示例 2:
提示:
SolutionLanguage: JavaScript 思路:后序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findFrequentTreeSum = function(root) {
const cnt = {};
const dfs = node => {
if (!node) return 0;
const s = node.val + dfs(node.left) + dfs(node.right);
cnt[s] ? cnt[s]++ : cnt[s] = 1;
return s;
}
dfs(root);
let maxCount = Math.max(...Object.values(cnt));
return Object
.entries(cnt)
.reduce((arr, [num, count]) => {
if (count === maxCount) arr.push(+num);
return arr;
}, [])
}; |
508. 出现次数最多的子树元素和DescriptionDifficulty: 中等 Related Topics: 树, 深度优先搜索, 哈希表, 二叉树 给你一个二叉树的根结点 一个结点的 「子树元素和」 定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。 示例 1:
示例 2:
提示:
SolutionLanguage: JavaScript /**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findFrequentTreeSum = function(root) {
}; |
题目链接: https://leetcode-cn.com/problems/most-frequent-subtree-sum
难度:
Medium
标签:
树
深度优先搜索
哈希表
二叉树
The text was updated successfully, but these errors were encountered: