码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Maximum Path Sum

时间:2015-08-02 23:11:15      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Runtime: 32ms.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxPathSum(TreeNode* root) {
13         maxSum = INT_MIN;
14         pathSum(root);
15         return maxSum;
16     }
17     int pathSum(TreeNode* root){
18         if(!root) return 0;
19         
20         int leftSum = pathSum(root->left);
21         int rightSum = pathSum(root->right);
22         int sum = root->val;
23         if(leftSum > 0) sum += leftSum;
24         if(rightSum > 0) sum += rightSum;
25         maxSum = max(sum, maxSum);
26         return max(leftSum, rightSum) > 0 ? max(leftSum, rightSum) + root->val : root->val;
27     }
28 private:
29     int maxSum;
30 };

 

Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4696771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!