码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Most Frequent Subtree Sum

时间:2018-09-27 22:04:48      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:app   更新   变量   递归   []   may   including   sign   eve   

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.

  我们想下子树有何特点,必须是要有叶结点,单独的一个叶结点也可以当作是子树,那么子树是从下往上构建的,这种特点很适合使用后序遍历,我们使用一个哈希表来建立子树和跟其出现频率的映射,用一个变量cnt来记录当前最多的次数,递归函数返回的是以当前结点为根结点的子树结点值之和,然后在递归函数中,我们先对当前结点的左右子结点调用递归函数,然后加上当前结点值,然后更新对应的哈希表中的值,然后看此时哈希表中的值是否大于等于cnt,大于的话首先要清空res,等于的话不用,然后将sum值加入结果res中即可,参见代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int count =0; 
    public int[] findFrequentTreeSum(TreeNode root) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        postOrder(root, map, list);
        int[] res = new int[list.size()];
        for(int i = 0; i<list.size(); i++){
            res[i] = list.get(i);
        }
        return res;
    }
    
    public int postOrder(TreeNode root, Map<Integer, Integer> map, List<Integer> res){
        if(root == null){
            return 0;
        }
        int left = postOrder(root.left, map, res);
        int right = postOrder(root.right, map, res);
        int sum = left+right+root.val;
        map.put(sum, map.getOrDefault(sum, 0)+1);
        if(map.get(sum) >= count){
            if(map.get(sum) > count){
                res.clear();
            }
            res.add(sum);
            count = map.get(sum);
        }
        return sum;
    }
}

 

LeetCode - Most Frequent Subtree Sum

标签:app   更新   变量   递归   []   may   including   sign   eve   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9715240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!