天天看点

leetcode解题之 508. Most Frequent Subtree Sum II java 版(求子树和)508. Most Frequent Subtree Sum

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.采用后序遍历,然后把所有的结果存到hashmap里面,同时用一个临时变量记录最大的次数是多少,最后遍历map就可以了。

int maxCount = 0;
	public int[] findFrequentTreeSum(TreeNode root) {
		Map<Integer, Integer> map = new HashMap<>();
		helper(root, map);
		// 控制结果输出,使用list转化为数组
		ArrayList<Integer> list = new ArrayList<Integer>();
		//求value为maxCount的所有value
		for (Entry<Integer, Integer> e : map.entrySet())
			if (e.getValue() == maxCount)
				list.add(e.getKey());
		int m[] = new int[list.size()];
		for (int i = 0; i < m.length; i++)
			m[i] = list.get(i);
		return m;
	}

	// 后续遍历
	private int helper(TreeNode root, Map<Integer, Integer> map) {
		if (root == null) {
			return 0;
		}
		// 子树和为结点和左右子树的和
		int sum = root.val
				+ helper(root.left, map)
				+ helper(root.right, map);
		// 使用map 记录结点数
		if (map.containsKey(sum))
			map.put(sum, map.get(sum) + 1);
		else
			map.put(sum, 1);
		// 记录最大结点
		maxCount = Math.max(maxCount, map.get(sum));
		return sum;
	}