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

二叉树中的最大路径和

时间:2016-01-20 06:18:13      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

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

样例

给出一棵二叉树:

       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 };

 

二叉树中的最大路径和

标签:

原文地址:http://www.cnblogs.com/whlsai/p/5143918.html

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