124 Binary Tree Maximum Path Sum

1 题目

Given a non-empty 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 must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

2 尝试解

2.1 分析

给定一个二叉树,问最大路径和。

以当前节点为根节点且经过根节点的最大路径和为局部最大路径和。从叶节点开始,节点15和7的局部最大路径分别为15和7;上升到节点20,局部最大路径为42(20+15+7);上升到节点-10,局部最大路径为34(-10+9+35)。

所以局部最大路径和tmp = max(root,root+left,root+right,root+left+right),用此更新结果result。其中left和right分别表示以左子节点和右子节点为路径一端的最大路径和。显然tmp并不能作为当前节点的返回值传递给其父节点,因为root+left+right的路径不能在root处分叉连结其父节点,只能返回max(root,root+left,root+right)。

所以在递归调用函数时,函数内部计算局部最大路径和,函数返回值是以根节点为一端的最大路径和。即

tmp = max(root,root+left,root+right,root+left+right) → result = max(result,tmp)

return max(root,root+left,root+right)

2.2 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int help(TreeNode* root, int&result){
        if(!root) return 0;
        int left = help(root->left,result);
        int right = help(root->right,result);
        int tmp = max(root->val,max(root->val+left,root->val+right));
        result = max(result,max(tmp,root->val+left+right));
        return tmp;
    }
    int maxPathSum(TreeNode* root) {
        int result = INT_MIN;
        help(root,result);
        return result;
    }
};

3 标准解

class Solution {
    int maxToRoot(TreeNode *root, int &re) {
        if (!root) return 0;
        int l = maxToRoot(root->left, re);
        int r = maxToRoot(root->right, re);
        if (l < 0) l = 0;
        if (r < 0) r = 0;
        if (l + r + root->val > re) re = l + r + root->val;
        return root->val += max(l, r);
    }
public:
    int maxPathSum(TreeNode *root) {
        int max = -2147483648;
        maxToRoot(root, max);
        return max;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值