题目描述:
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must containat least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
题目解析:
题目意思是从左子树到右子树找一条和最大的路径并求和,我们只要设置一个全局变量并递归下去求和即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int global_max = -10000;
int maxPathSum(TreeNode* root) {
if(root == NULL)
return 0;
maxSum(root);
return global_max;
}
int maxSum(TreeNode* root)
{
if(root == NULL)
return 0;
int local_max = root->val;
int left_max = maxSum(root->left);
int right_max = maxSum(root->right);
if(left_max > 0)
local_max += left_max;
if(right_max > 0)
local_max += right_max;
if(local_max > global_max)
global_max = local_max;
return max(root->val,max(root->val + left_max, root->val + right_max ));
}
};