124. Binary Tree Maximum Path Sum
- Total Accepted: 90097
- Total Submissions: 354576
- Difficulty: Hard
- Contributors: Admin
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 contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
自我分析:对于这种二叉树的问题很适合用递归的方法来实现,求最大的路径和,所以是考虑到负值的情况,路径是唯一的,所以只要对左右分别进行递归,找出唯一的最大路径和最后左右相加即可。
代码如下:
int Path(TreeNode* root,int&maxSum)
{
if(root==NULL)
return 0;
int leftmax = Path(root->left,maxSum);
int rightmax = Path(root->right,maxSum);
maxSum = max(maxSum,max(0,leftmax)+max(0,rightmax)+root->val);
return max(0,max(leftmax,rightmax))+root->val;
}
int maxPathSum(TreeNode *root) {
int maxSum = INT_MIN;
Path(root,maxSum);
return maxSum;
}