面试算法-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;
    }
}
相关推荐
C_player_00115 分钟前
——贪心算法——
c++·算法·贪心算法
不要再敲了1 小时前
JDBC从入门到面试:全面掌握Java数据库连接技术
java·数据库·面试
kyle~2 小时前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Boop_wu2 小时前
[数据结构] 队列 (Queue)
java·jvm·算法
Nan_Shu_6142 小时前
Web前端面试题(1)
前端·面试·职场和发展
hn小菜鸡2 小时前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
围巾哥萧尘3 小时前
开发一个AI婚礼照片应用时,如何编写和调整提示词🧣
面试
大前端helloworld3 小时前
前端梳理体系从常问问题去完善-基础篇(html,css,js,ts)
前端·javascript·面试
ゞ 正在缓冲99%…3 小时前
leetcode101.对称二叉树
算法