力扣考题汇总

标题#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;
    }
}```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值