Leetcode124. 二叉树中的最大路径和

101 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招系列活动-刷题打卡任务,点击查看活动详情

一、题目描述:

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

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

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

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/bi…

二、思路分析:

本人思路,定义res为最后答案。在每个节点上加上一个max属性,代表从底到该节点单线最大值。

三、AC 代码:

 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxPathSum = function(root) {
    let res=root.val;
    dfs(root);
    return res;
    function dfs(root){
        if(root){
            dfs(root.left);
            dfs(root.right);
            root.max=root.val;
            if(root.left){
                root.max=Math.max(root.max,root.val+root.left.max);
            }
            if(root.right){
                root.max=Math.max(root.max,root.val+root.right.max);
            }
            res=Math.max(root.max,res);
            if(root.left&&root.right){
                res=Math.max(res,root.val+root.left.max+root.right.max,root.max)
            }
        }
    }
};

四、总结:

感觉写的麻烦了点,但是蛮好理解的。