leetcode 508 && 可以将 数组 转化为二叉树
package com.javamvc.learning.leetcode;
import java.util.HashMap;
import java.util.Map;
public class leetCode508 {
static class TreeNode {
TreeNode left;
TreeNode right;
int val;
TreeNode(int val) {
this.val = val;
}
public static void main(String[] args) {
Integer[] arr = new Integer[] { 5, 2, -3, 5, -6, 5 };
TreeNode root = createBinaryTreeByArray(arr, 0);
Solution solution = new Solution();
int[] findFrequentTreeSum = solution.findFrequentTreeSum(root);
for (int i : findFrequentTreeSum) {
System.out.println(i);
}
}
static TreeNode createBinaryTreeByArray(Integer[] array, int index) {
TreeNode tn = null;
if (index < array.length) {
Integer value = array[index];
if (value == null) {
return null;
}
tn = new TreeNode(value);
tn.left = createBinaryTreeByArray(array, 2 * index + 1);
tn.right = createBinaryTreeByArray(array, 2 * index + 2);
return tn;
}
return tn;
}
static class Solution {
private Map<Integer, Integer> map = new HashMap<>();
private int degree = 0; // the highest frequency of the sum
private int size = 0; // to determine the number of most frequent sum
public int[] findFrequentTreeSum(TreeNode root) {
findSum(root); // post order traversal
int[] res = new int[size];
int i = 0;
// putting all the element into the final array
for (int n : map.keySet()) {
if (map.get(n) == degree) {
res[i++] = n;
}
}
return res;
}
public int findSum(TreeNode node) {
// when node == null, the sum = 0
if (node == null) {
return 0;
}
int left = findSum(node.left); // find the sum of the left subtree
int right = findSum(node.right); // find the sum of the right subtree
int sum = left + right + node.val; // find the sum of the tree rooted by node
map.put(sum, map.getOrDefault(sum, 0) + 1);
System.out.println(map.size());
System.out.println(map.values());
for (int m = 0; m < map.size(); m++) {
System.out.println(map.keySet() + "\t23569569");
}
if (map.get(sum) > degree) {
degree = map.get(sum); // update the highest frequency
size = 1; // the number of sum with this frequency is reset back to 1
} else if (map.get(sum) == degree) {
size++; // increase the number of the most frequent sum
}
return sum;
}
}
}}