[leetcode] 124. 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

Return6.

这道题是计算二叉树最大路径和,题目难度为Hard。

基于二叉树数据结构的特性,我们知道最大路径和的路径肯定存在一个自己的根节点,它的左右子树(形似链表)即是路径的左右两部分,这点需要大家首先确认。这样我们以每个节点作为此根节点,分别计算从它的左右子树开始的最大路径和,之后加上此根节点值即是此根节点确定的最大路径和。这里需要注意如果左右子树的最大路径和是负数,则抛弃这个子树的路径,因为加上它会使路径和变小,把这个子树的路径和记为0即可。这样深度优先遍历二叉树即可比较获得最大路径和。具体代码:

class Solution {
    int getMaxPathSum(TreeNode* root, int& maxSum) {
        if(!root) return 0;
        int left = max(getMaxPathSum(root->left, maxSum), 0);
        int right = max(getMaxPathSum(root->right, maxSum), 0);
        maxSum = max(maxSum, left+right+root->val);
        return max(left, right) + root->val;
    }
public:
    int maxPathSum(TreeNode* root) {
        if(!root) return 0;
        int maxSum = INT_MIN;
        getMaxPathSum(root, maxSum);
        return maxSum;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值