代码改变世界

leetcode - Binary Tree Maximum Path Sum

2013-03-05 21:04  张汉生  阅读(189)  评论(0编辑  收藏  举报

题目描述:点击此处

 1 /**
 2  * Definition for binary tree
 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 getValue(TreeNode * node, int & endValue){
13     endValue = 0;
14     if (node==NULL){
15       return 0;
16     }
17     int rlt = node->val;
18     int leftValue = -1000000000;
19     int rightValue = -1000000000;
20     int leftEv=0, rightEv=0;
21     if (node->left != NULL)
22       leftValue = getValue(node->left, leftEv);
23     if (node->right != NULL)
24       rightValue = getValue(node->right, rightEv);
25     if (leftEv>0)
26       rlt += leftEv;
27     if (rightEv>0)
28       rlt += rightEv;
29     if (leftValue>rlt)
30       rlt = leftValue;
31     if (rightValue>rlt)
32       rlt = rightValue;
33     endValue = node->val + max(0, max(leftEv,rightEv));
34     return rlt;
35   }
36   int maxPathSum(TreeNode *root) {
37     // Start typing your C/C++ solution below
38     // DO NOT write int main() function
39     if (root == NULL)
40       return 0;
41     int value;
42     return getValue(root, value);
43   }
44 };