标签:
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 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4696771.html