首页 > 其他 > 详细

[Leetcode] Binary Tree Maximum Path Sum

时间:2014-04-04 05:50:20      阅读:424      评论:0      收藏:0      [点我收藏+]

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.

后序遍历!

bubuko.com,布布扣
 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 myMax(int a, int b, int c) {
13         a = a > b ? a : b;
14         return a > c ? a : c;
15     }
16     
17     int getMaxSum(TreeNode *root, int &max_sum) {
18         if (root == NULL) {
19             return 0;
20         }
21         int local_max = root->val;
22         int left = getMaxSum(root->left, max_sum);
23         int right = getMaxSum(root->right, max_sum);
24         local_max += (left > 0) ? left : 0;
25         local_max += (right > 0) ? right : 0;
26         max_sum = max_sum > local_max ? max_sum : local_max;
27         return myMax(root->val, root->val + left, root->val + right);
28     }
29     
30     int maxPathSum(TreeNode *root) {
31         int max_sum = INT_MIN;
32         getMaxSum(root, max_sum);
33         return max_sum;
34     }
35 };
bubuko.com,布布扣

 

[Leetcode] Binary Tree Maximum Path Sum,布布扣,bubuko.com

[Leetcode] Binary Tree Maximum Path Sum

原文:http://www.cnblogs.com/easonliu/p/3642942.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!