标题#6308. 二叉树中的第 K 大层和
标题##题目
给你一棵二叉树的根节点 root 和一个正整数 k 。
树中的 层和 是指 同一层 上节点值的总和。
返回树中第 k 大的层和(不一定不同)。如果树少于 k 层,则返回 -1 。
注意,如果两个节点与根节点的距离相同,则认为它们在同一层。
标题##说明
这题别用数组,小了装不下,大了 内存溢出
涉及的知识点:二叉树深度优先遍历(DFS)和广度优先遍历(BFS)
https://www.jianshu.com/p/a753d5c733ec
标题##代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.*;
class Solution {
private HashMap<Integer, Long> map = new HashMap<Integer, Long>();
public long kthLargestLevelSum(TreeNode root, int k) {
if (root == null) {
return -1;
}
TreeNode current = root;
int position = 0;
calculate(position, current);
List<Long> list = new ArrayList<>(map.values());
Collections.sort(list, Collections.reverseOrder());
//Arrays.sort(result, new myCompare());
System.out.println("result =" + list.size());
if (list.size() < k) {
return -1;
}
return list.get(k-1);
}
//实际未用到
class myCompare implements Comparator<Long> {
@Override
public int compare(Long a, Long b) {
if (a != null && b != null) {
return (int)(b - a);
} else if (a != null && b == null) {
return -1;
} else if(a ==null && b != null){
return 1;
} else {
return -1;
}
}
}
public int calculate(int position, TreeNode currentNode) {
if (currentNode != null) {
TreeNode left = currentNode.left;
TreeNode right = currentNode.right;
if (!map.containsKey(position)) {
map.put(position, Long.valueOf(currentNode.val) );
} else {
Long data = map.get(position);
long value1 = data.longValue();
value1 += currentNode.val;
data = Long.valueOf(value1);
map.put(position, data);
}
if (left != null) {
int i = position + 1;
calculate(i, left);
}
if (right != null) {
int j = position + 1;
calculate(j, right);
}
}
return position;
}
}```