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

LeetCode: Binary Tree Maximum Path Sum

时间:2014-08-25 22:34:54      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   strong   for   ar   art   

LeetCode: Binary Tree Maximum Path Sum

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.

地址:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

算法:用递归来解决。首先,最大的路径和出现在以下三种情况:1)出现在左子树中;2)出现在右子树;3)经过根节点,在这种情况下,相当与左边从根节点到叶节点的最大路径加上右边从根节点到叶节点的最大路径。

对于第三种情况也可以用递归来解决。代码:

 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 maxPathSum(TreeNode *root) {
13         if(!root){
14             return INVALID;
15         }
16         int left = maxPathSum(root->left);
17         int right = maxPathSum(root->right);
18         int mid = root->val;
19         int mid_left =maxLoadSum(root->left);
20         if(mid_left > 0){
21             mid += mid_left;
22         }
23         int mid_right = maxLoadSum(root->right);
24         if(mid_right > 0){
25             mid += mid_right;
26         }
27         if(left != INVALID && left > mid){
28             mid = left;
29         }
30         if(right != INVALID && right > mid){
31             mid = right;
32         }
33         return mid;
34     }
35     int maxLoadSum(TreeNode *root){
36         if(flag.find(root) != flag.end()){
37             return flag[root];
38         }
39         if(!root){
40             flag[root] = -1;
41             return -1;
42         }
43         int sum = root->val;
44         int left = maxLoadSum(root->left);
45         int right = maxLoadSum(root->right);
46         if (left > right){
47             right = left;
48         }
49         if(right > 0){
50             sum += right;
51         }
52         flag[root] = sum;
53         return sum;
54     }
55     static const int INVALID = 0x7FFFFFFF;
56     map<TreeNode *,int> flag;
57 };

 

LeetCode: Binary Tree Maximum Path Sum

标签:style   blog   http   color   io   strong   for   ar   art   

原文地址:http://www.cnblogs.com/boostable/p/leetcode_binary_tree_maximum_path_sum.html

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