[leetcode]Binary Tree Maximum Path Sum

 

#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;



struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

/*本题心得:
0 如何分析一个问题
1 没有固定格式的判断方式
2 越界
*/

class Solution {
public:
    int maxPathSum(TreeNode *root) {
        int pathLen = 0;
        return maxPathSumCore(root, pathLen);
    }

    int maxPathSumCore(TreeNode *root, int &pathLen){//pathLen代表从root到下面某个节点的最大距离
        if (!root){
            pathLen = 0;
            return 0;
        }

        int leftPathLen;//左子树中某个节点往上走,走到左孩子的最大sum(还未形成path,还可和root甚至右孩子结合)
        int leftSum;//左子树的某个最大sum(已经形成一个path了)
        if (root->left)
            leftSum = maxPathSumCore(root->left, leftPathLen);
        else{
            leftSum = INT_MIN;//左子树的sum(独立path)必须是最负,不能为0,不然如果左孩子是空,但是这里置0,然后leftSum作为独立一个元素,返回给上层时,上层用这个leftSum和root比较,发现比root(root为负数)大,就把root覆盖了
            leftPathLen = 0;//左孩子的path可以为0,因为左孩子如果是叶子,会在和
        }

        int rightPathLen;
        int rightSum;
        if (root->right)
            rightSum = maxPathSumCore(root->right, rightPathLen);
        else{
            rightSum = INT_MIN;
            rightPathLen = 0;
        }
        
        pathLen = std::max(root->val, root->val + std::max(leftPathLen, rightPathLen));//到root的最大path,要么是root,要么是root+左子树到左孩子最大值,要么是root+右子树到右孩子最大值(root一定被包含)

        int tmp = root->val;
        if (leftPathLen > 0)//如果某个子树的path最大值为负,那么加上也没意义
            tmp += leftPathLen;
        if (rightPathLen > 0)
            tmp += rightPathLen;
        int result = std::max(std::max(root->val, tmp), std::max(leftSum, rightSum));//整体的最大path,1 root;2 通过root的左最大path和/或右最大path;3 左子树中的整体最大path或右子树中的整体最大path

        return result;
    }
};


int main()
{
    TreeNode n1(1);
    TreeNode n2(-2);
    n1.left = &n2;
    Solution s;
    s.maxPathSum(&n1);
    return 0;
}

 

 

 

 

 

EOF

posted on 2012-12-18 23:48  kkmm  阅读(868)  评论(0编辑  收藏  举报