LeetCode:124二叉树中的最大路径和

java 复制代码
/**
 * 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;
 *     }
 * }
 */
class Solution {
    //记录最终的最大路径和,初始为极小值,防范全树都为负数的情况
    int maxSum = Integer.MIN_VALUE;
        
    public int maxPathSum(TreeNode root) {
        calculateSinglePath(root);
        return maxSum;
    }
    //计算当前节点能为父节点提供的最大路径和
    private int calculateSinglePath(TreeNode node){
        if(node == null){
            return 0;
        }
        //递归计算左右子树
        int leftProfit = Math.max(0,calculateSinglePath(node.left));
        int rightProfit = Math.max(0,calculateSinglePath(node.right));
        //倒V型的内部和
        int currentInternalSum = leftProfit + node.val + rightProfit;

        maxSum = Math.max(maxSum, currentInternalSum);

        return node.val + Math.max(leftProfit,rightProfit);
    }
}

maxSum用于记录全局最终的最大值;而函数返回值用于记录局部最大值,往上传递给父节点

相关推荐
闲猫2 小时前
Spring AI 对接Deepseek ChatModel 聊天对话
java·前端·spring
海石2 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石3 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
自信的未来4 小时前
JSON 工具|Web Worker 工程化打包 + 语法自动修复 + 多语言代码生成实战
java·前端·json
Brookty4 小时前
【JavaEE】线程安全(一).4:写块串行保安全、CAS
java·开发语言·java-ee·多线程·线程安全
Jerry4 小时前
LeetCode 151. 反转字符串中的单词
算法
怕孤单的草丛5 小时前
缓存管理面临的主要问题
java·数据库·缓存
gugucoding5 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL6 小时前
我的数据结构3——链表(link list)
数据结构·链表