首页 > 代码库 > Binary Tree Maximum Path Sum

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.

 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