二叉树中的最大路径和

给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)

样例

给出一棵二叉树:

       1
      / \
     2   3

返回 6

 1 class Solution {
 2 public:
 3     /**
 4      * @param root: The root of binary tree.
 5      * @return: An integer
 6      */
 7     struct ResultType {
 8         int maxLength;
 9         int maxSinglePath;
10         ResultType(int a, int b) : maxLength(a), maxSinglePath(b) {}
11     };
12     int maxPathSum(TreeNode *root) {
13         if (root == NULL) {
14             return 0;
15         }
16         return helper(root).maxLength;
17     }
18     
19     ResultType helper(TreeNode *root) {
20         if (root == NULL) {
21             return ResultType(INT_MIN, INT_MIN);
22         }
23         
24         ResultType left = helper(root->left);
25         ResultType right = helper(root->right);
26         
27         int maxSinglePath = std::max(0, std::max(left.maxSinglePath, right.maxSinglePath))
28                             + root->val;
29         int maxCrossLength = std::max(0, left.maxSinglePath)
30                             + std::max(0, right.maxSinglePath) 
31                             + root->val;
32         int maxLength = std::max(left.maxLength, right.maxLength);
33         maxLength = std::max(maxLength, maxCrossLength);
34         return ResultType(maxLength, maxSinglePath);
35     }
36 };

 

posted on 2016-01-20 01:47  manfeyn  阅读(431)  评论(0)    收藏  举报

导航