Leetcode Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

对于每个结点,我们需要比较三个值。

  • 左结点为结尾的路径和+当前结点值
  • 右结点为结尾的路径和+当前结点值
  • 当前结点值

取这个三个值作为以当前节点为结尾的最大路径和返回。

同时获取以当前结点为根的子树的最大路径和,其子树最大路径来源于

  • 以当前结点为结尾的最大路径和(也就是上面结点所述的值)
  • 左节点为结尾的路径和+当前结点值+右结点为结尾的路径和
  • 左子树的最大路径和
  • 右子树的最大路径和

取其4个值中得最大值作为子树的最大路径和。

class Solution {
public:
    int maxSum = INT_MIN;
    int getMaxSum(TreeNode* root){
        if(root == NULL) return 0;
        int leftSum = getMaxSum(root->left), rightSum = getMaxSum(root->right);
        int curSum =  max(root->val, max(root->val+leftSum, root->val+rightSum));
        maxSum = max(maxSum,max(curSum,root->val+leftSum+rightSum));
        return curSum;
    }

    int maxPathSum(TreeNode *root){
        getMaxSum(root);
        return maxSum;
    }
};

 

posted @ 2014-07-01 21:20  OpenSoucre  阅读(166)  评论(0编辑  收藏  举报