leetcode Binary Tree Maximum Path Sum

给定一颗数,然后任意的起点或者终点,找到最大的路径和。例如:

Given the below binary tree,

       1
      / 
     2   3

Return 6.

一看到是标hard的题目就觉得要吃力才能搞出来。果然,经过不懈奋斗,成功从Time Limited到AC。

我看到这题的第一思路就是递归:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
//给定一个节点,返回左边单路径或者右边路径包括当前值的最(往上传用的),如果下面两边小于零则值返回自己的值
int oneSide(TreeNode *root)
{
    if (!root) return 0;
    if (!root -> left && !root -> right) return root -> val > 0 ? root -> val : 0; 
    else
    {
        int val = max(oneSide(root -> left), oneSide(root -> right));
        val = val > 0 ? val + root -> val : root -> val;
        return val > 0 ? val : 0;
    }
}
int curMax(TreeNode *root)
{
    if (!root) return 0;
    return root -> val + oneSide(root -> left) + oneSide(root -> right);
}
//对每个节点遍历求左右两个节点的做大加上本身,然后取最大的值就是maximum path sum了
int maxPathSum(TreeNode *root)
{
    if (!root) return 0;
    int tmpl = INT_MIN, tmpr = INT_MIN;
    int cur = curMax(root);
    if (root -> left)
        tmpl = maxPathSum(root -> left);
    if (root -> right)
        tmpr = maxPathSum(root -> right);
    if (cur > tmpl)
        return (cur > tmpr ? cur : tmpr);
    else
        return (tmpl > tmpr ? tmpl : tmpr);
}
};

果断超时了,然后静下心想了调,约两个小时终于终于做出来啦哈哈。

其实就是进行一次递归的时候同时记录最大值,然后递归完最大值就出来了,所以比之前的递归快了好多。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
int oneSide2(TreeNode *root, int &maxP)
{
    if (!root) return 0;
    if (!root -> left && !root -> right)
    {
        maxP = maxP > root -> val ? maxP : root -> val;
        return root -> val > 0 ? root -> val : 0;
    }
    else
    {
        int lf = oneSide2(root -> left, maxP), ri = oneSide2(root ->right, maxP);
        lf = lf > 0 ? lf : 0; ri = ri > 0 ? ri : 0;
        if (lf + ri + root -> val > maxP) maxP = lf + ri + root -> val;
        return root -> val + max(lf, ri) > 0 ? root -> val + max(lf, ri) : 0;
    }
}
int maxPathSum(TreeNode *root)
{
    if (!root) return 0;
    int maxP = INT_MIN;
    oneSide2(root, maxP);
    return maxP;
}
};
原文地址:https://www.cnblogs.com/higerzhang/p/4141553.html