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

Binary Tree Maximum Path Sum

时间:2014-10-26 14:18:14      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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.

 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 max(int a, int b)
13     {
14         return a > b? a : b;
15     }
16 
17     int maxPathSum(TreeNode *root) {
18         if (!root)
19             return 0;
20         int val,ll,rr;
21         ll = rr = 0;
22         val = -65535;
23         if (root->left)
24         {
25             val = max(val,maxPathSum(root->left));
26             ll = max(0,root->left->val);
27         }
28         if (root->right)
29         {
30             val = max(val,maxPathSum(root->right));
31             rr = max(0,root->right->val);
32         }
33         val = max(val,root->val + ll + rr);
34         root->val += max(ll,rr);
35         return val;
36     }
37 };

先计算左子节点到叶子节点最大值,在计算右子节点到叶子节点最大值,最后计算根节点最大值,val代表所求最大值

要更新当前节点到叶节点的最大路径值,考虑负数情况

Binary Tree Maximum Path Sum

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/george-cw/p/4051888.html

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