gpt4 book ai didi

LeetCode_二叉树_困难_124. 二叉树中的最大路径和

转载 作者:知者 更新时间:2024-03-13 08:54:03 28 4
gpt4 key购买 nike

1.题目

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

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

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

示例 1:

输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

示例 2:

输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

提示:
树中节点数目范围是 [1, 3 * 104]
-1000 <= Node.val <= 1000

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-maximum-path-sum

2.思路

(1)后序遍历

3.代码实现(Java)

//思路1————后序遍历
/**
 * 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 res = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        oneSideMax(root);
        return res;
    }

    public int oneSideMax(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftMaxSum = Math.max(0, oneSideMax(root.left));
        int rightMaxSum = Math.max(0, oneSideMax(root.right));
        //后序遍历位置,顺便更新最大路径和
        int pathMaxSum = root.val + leftMaxSum + rightMaxSum;
        res = Math.max(pathMaxSum, res);
        /*
            实现函数定义,左右子树的最大单边路径和加上当前根节点的值
            就是从当前根节点 root 为起点的最大单边路径和
        */
        return Math.max(leftMaxSum, rightMaxSum) + root.val;
    }
}

创作打卡挑战赛

赢取流量/现金/CSDN周边激励大奖

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com