leetcode题解-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,-3,(5+2+(-3))=4。因为个数都是1,所有就把这三个和都返回。而第二个例子子树和分别为2,-5,(5+2-5)=2,和为2的有两个,所以只返回2。
这好似一道典型的深度遍历的题目。要想获得所有子树的和,最简单的方法是从叶子节点开始向上求,但是题目中给的是树的根节点,所以先遍历到其叶子节点在进行回溯。代码如下:

public class Solution {
    Map sumToCount;
    int maxCount;

    public int[] findFrequentTreeSum(TreeNode root) {
        maxCount = 0;
        sumToCount = new HashMap();

        postOrder(root);

        List res = new ArrayList<>();
        for (int key : sumToCount.keySet()) {
            if (sumToCount.get(key) == maxCount) {
                res.add(key);
            }
        }

        int[] result = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            result[i] = res.get(i);
        }
        return result;
    }

    private int postOrder(TreeNode root) {
        if (root == null) return 0;
        //遍历左树,并返回左树的和
        int left = postOrder(root.left);
        //遍历右树,并返回右树的和
        int right = postOrder(root.right);
        //加上本节点值,将其保存到Map中并返回上一层节点
        int sum = left + right + root.val;
        int count = sumToCount.getOrDefault(sum, 0) + 1;
        sumToCount.put(sum, count);

        maxCount = Math.max(maxCount, count);

        return sum;
    }
}

这段程序击败了32%的用户。但我也只想到了这一种解题的思路,而且在网上也并未找到更好的解题思路。所以就先这样吧。

你可能感兴趣的:(leetcode刷题,leetcode)