Skip to content
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

Open
webVueBlog opened this issue Jun 19, 2022 · 2 comments

Comments

@webVueBlog
Copy link
Collaborator

题目链接: https://leetcode-cn.com/problems/most-frequent-subtree-sum

难度: Medium
标签: 深度优先搜索 哈希表 二叉树

@dreamjean
Copy link
Collaborator

dreamjean commented Jun 19, 2022

508. 出现次数最多的子树元素和

Description

Difficulty: 中等

Related Topics: , 深度优先搜索, 哈希表, 二叉树

给你一个二叉树的根结点 root ,请返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)。

一个结点的 「子树元素和」 定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。

示例 1:

输入: root = [5,2,-3]
输出: [2,-3,4]

示例 2:

输入: root = [5,2,-5]
输出: [2]

提示:

  • 节点数在 [1, 104] 范围内
  • -105 <= Node.val <= 105

Solution

Language: 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;
        }, [])
};

@webVueBlog
Copy link
Collaborator Author

webVueBlog commented Jun 19, 2022

508. 出现次数最多的子树元素和

Description

Difficulty: 中等

Related Topics: , 深度优先搜索, 哈希表, 二叉树

给你一个二叉树的根结点 root ,请返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)。

一个结点的 「子树元素和」 定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。

示例 1:

输入: root = [5,2,-3]
输出: [2,-3,4]

示例 2:

输入: root = [5,2,-5]
输出: [2]

提示:

  • 节点数在 [1, 104] 范围内
  • -105 <= Node.val <= 105

Solution

Language: 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) {

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants