LeetCode124—Binary Tree Maximum Path Sum

本文详细解析了LeetCode124题BinaryTreeMaximumPathSum的解题思路及算法实现,介绍了如何通过深度优先搜索寻找二叉树中的最大路径和,并强调了路径选取的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode124—Binary Tree Maximum Path Sum

原题

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

   1
  / \
 2   3

Return 6.

分析

参考:http://blog.youkuaiyun.com/linhuanmars/article/details/22969069
这题确实有点难,刚开始以为树的深度遍历序列中找到和最大子序列,这样进行一次深度优先搜索将结果存在数组中,在对数组做一次最大子序列和运算(考虑节点值可能有负数),然而题目的要求并不是这样的。

题目要求是:要在树中找一条连通的通路,其值最大

对于树中的某个节点来说,需要考虑两件事情:1是记录到该节点时权值是多少(并实时更新最大值),2是记录经过这个节点的路径来自于左孩子还是右孩子,这两件事情一定要分别计算,最大值要算上左右孩子,但是路径只能是左孩子或者右孩子的其中之一。

代码

class Solution {
    int dfs(TreeNode* root,int &maxSum)
    {
        if (root == NULL)
            return 0;
        int left = dfs(root->left,maxSum);
        int right = dfs(root->right,maxSum);
        int rootval = root->val + max(0, left) + max(0,right);
        if (maxSum < rootval)
            maxSum = rootval;
    //  return rootval;
        return root->val + max(max(left,right),0);
    }
public:
    int maxPathSum(TreeNode* root) {
        int maxSum = root->val;
        dfs(root,maxSum);
        return maxSum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值