zoukankan      html  css  js  c++  java
  • 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.

    Examples 1
    Input:

      5
     /  
    2   -3
    
    return [2, -3, 4], since all the values happen only once, return all of them in any order.

    Examples 2
    Input:

      5
     /  
    2   -5
    
    return [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.

    给出二叉树的根,要求找到最常见的子树总和。节点的子树总和被定义为由根节点(包括节点本身)的子树形成的所有节点值之和。那么最常见的子树总和值是多少?如果有关系,则以任何顺序返回所有频率最高的值。

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val) {
    4. * this.val = val;
    5. * this.left = this.right = null;
    6. * }
    7. */
    8. /**
    9. * @param {TreeNode} root
    10. * @return {number[]}
    11. */
    12. var findFrequentTreeSum = function(root) {
    13. let max = 0;
    14. let res = [];
    15. let m = {};
    16. let helper = (node) => {
    17. if (!node) return 0;
    18. let left = helper(node.left);
    19. let right = helper(node.right);
    20. let sum = left + right + node.val;
    21. if (m[sum]) {
    22. m[sum]++;
    23. } else {
    24. m[sum] = 1;
    25. }
    26. max = Math.max(m[sum], max);
    27. return sum;
    28. }
    29. helper(root);
    30. for (let i in m) {
    31. if (m[i] == max) {
    32. res.push(parseInt(i));
    33. }
    34. }
    35. return res;
    36. };







  • 相关阅读:
    一些小问题的解决
    JavaScript面向对象的支持
    HTML 5 会为 Flash 和 Silverlight 送终吗?
    Web Forms 2.0 行将被 HTML 5 代替
    XHTML 2: 出师未捷身先死, HTML 5:万千宠爱于一身
    Javascript 技巧大全
    深入了解 HTML 5
    HTML 5 令人期待的 5 项功能
    SQL SERVER 2005中的Schema详解
    VS2008 ,TFS2008破解序列号
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7652663.html
Copyright © 2011-2022 走看看