【LeetCode 面试经典150题】124. Binary Tree Maximum Path Sum 二叉树中最大路径和

124. Binary Tree Maximum Path Sum

题目大意

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

中文释义

在二叉树中,一条路径是指节点序列,其中序列中每对相邻的节点之间都有一条边连接。一个节点在序列中最多只能出现一次。注意,路径不需要通过根节点。

路径的路径和是该路径上所有节点值的总和。

给定一个二叉树的根节点,返回任何非空路径的最大路径和。

示例

示例 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 * 10^4]
  • -1000 <= Node.val <= 1000

解题思路

方法

该方法通过递归地遍历二叉树的每个节点,计算以每个节点为根的子树的最大路径和。

  1. 递归函数 maxPathDown

    • 实现 maxPathDown 函数递归地计算从当前节点到叶节点的最大路径和。
    • 函数同时更新一个引用参数 maxSum,它记录遍历过程中的最大路径和。
  2. 处理左右子树

    • 计算左子树和右子树的最大路径和,忽略负值路径和。
  3. 更新最大路径和

    • 更新 maxSum 为当前节点值加上左右子树的最大路径和,如果这个总和大于当前的 maxSum
  4. 返回节点的最大贡献值

    • 返回当前节点的值加上左右子树中较大的路径和。
  5. 计算总的最大路径和

    • maxPathSum 函数中,初始化 maxSum 为最小整数值,然后调用 maxPathDown 函数并返回 maxSum

代码

class Solution {
public:
    int maxPathDown(TreeNode* root, int& maxSum) {
        if (root == nullptr) return 0;

        int left = max(0, maxPathDown(root -> left, maxSum));
        int right = max(0, maxPathDown(root -> right, maxSum));
        maxSum = max(maxSum, left + right + root -> val);

        return max(left, right) + root -> val;
    }
    int maxPathSum(TreeNode* root) {
        int maxSum = INT_MIN;
        maxPathDown(root, maxSum);
        return maxSum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值