面试算法-59-二叉树中的最大路径和

题目

二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和 。

示例 1:

输入:root = [1,2,3]

输出:6

解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

java 复制代码
class Solution {
    public int maxPathSum(TreeNode root) {
        int[] max = { Integer.MIN_VALUE };
        dfs(root, max);
        return max[0];
    }

    public Integer dfs(TreeNode root, int[] max) {
        if (root == null) {
            return 0;
        }

        int[] maxLeft = { Integer.MIN_VALUE };
        int left = Math.max(0, dfs(root.left, maxLeft));
        int[] maxRight = { Integer.MIN_VALUE };
        int right = Math.max(0, dfs(root.right, maxRight));

        max[0] = Math.max(maxLeft[0], maxRight[0]);
        max[0] = Math.max(max[0], left + root.val + right);
        return Math.max(left, right) + root.val;
    }
}
相关推荐
浮灯Foden25 分钟前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
西工程小巴1 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程1 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit1 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
小奋斗2 小时前
深入浅出:ES5/ES6+数组扁平化详解
javascript·面试
掘金安东尼2 小时前
解读 hidden=until-found 属性
前端·javascript·面试
前端小白19953 小时前
面试取经:工程化篇-webpack性能优化之热替换
前端·面试·前端工程化
百度Geek说3 小时前
第一!百度智能云领跑视觉大模型赛道
算法
洛卡卡了3 小时前
数据库加密方案实践:我们选的不是最完美,但是真的够用了。
数据库·后端·面试
big_eleven3 小时前
轻松掌握数据结构:二叉树
后端·算法·面试