标签:
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
.
前序遍历,计算出最大值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 int preOrder(struct TreeNode* root, int *maxSum) { 11 int leftSum = 0, rightSum = 0, partSum = 0, sum = 0; 12 13 if(!root) return 0; 14 15 leftSum = preOrder(root->left, maxSum); 16 rightSum = preOrder(root->right, maxSum); 17 18 partSum = root->val; 19 sum = rightSum + leftSum + root->val; 20 if(leftSum > rightSum && leftSum > 0) { 21 partSum += leftSum; 22 } 23 else if(rightSum > leftSum && rightSum > 0) { 24 partSum += rightSum; 25 } 26 if(*maxSum < partSum){ 27 *maxSum = partSum; 28 } 29 if(*maxSum < sum){ 30 *maxSum = sum; 31 } 32 33 return partSum; 34 } 35 36 int maxPathSum(struct TreeNode* root) { 37 if(!root) return 0; 38 39 int maxSum = root->val; 40 preOrder(root, &maxSum); 41 42 return maxSum; 43 }
92 / 92 test cases passed.
|
Status:
Accepted |
Runtime: 20 ms
|
最后运行时间是20ms,但是看到统计图里有大神的代码只耗时16ms,看来是还有什么高级解法,希望看到本文的大神指点下啊!
[LeetCode]Binary Tree Maximum Path Sum
标签:
原文地址:http://www.cnblogs.com/zhangzhiqi/p/4765136.html