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.

在p节点为根的子树下,以p为端点的最大路径和为f(p),则有

f(p) = max{ f(p->left)+p->val, f(p->right)+p->val, p->val }

那么在p节点为根的子树下,最大路径和 经过p的 就是 max{ f(p), f(p->left) + p->val + f(p->right) }

So 以root为根的树下,最大路径和既是求,当p=所有节点时,最大路径和的最大值,代码如下:

 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         ans = -0x3fffffff;  //节点值可能为负数
14         postOrder(root);    //需要后序遍历整棵树
15         return ans;
16     }
17 
18     int postOrder(TreeNode* root) {
19         if( !root ) return 0;
20         int il = postOrder(root->left);
21         int ir = postOrder(root->right);
22         int ret = max( root->val, max( il+root->val, ir+root->val) );   //计算公式看讲解
23         ans = max( ans, max(ret, il+ir+root->val) );
24         return ret;
25     }
26 private:
27     int ans;
28 };

 

posted on 2014-08-22 16:53  bug睡的略爽  阅读(119)  评论(0编辑  收藏  举报

导航