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 does not need to go through the root.
For example:
Given the below binary tree,
1
/ \ 2 3
Return6.
这道题是计算二叉树最大路径和,题目难度为Hard。
基于二叉树数据结构的特性,我们知道最大路径和的路径肯定存在一个自己的根节点,它的左右子树(形似链表)即是路径的左右两部分,这点需要大家首先确认。这样我们以每个节点作为此根节点,分别计算从它的左右子树开始的最大路径和,之后加上此根节点值即是此根节点确定的最大路径和。这里需要注意如果左右子树的最大路径和是负数,则抛弃这个子树的路径,因为加上它会使路径和变小,把这个子树的路径和记为0即可。这样深度优先遍历二叉树即可比较获得最大路径和。具体代码:
class Solution {
int getMaxPathSum(TreeNode* root, int& maxSum) {
if(!root) return 0;
int left = max(getMaxPathSum(root->left, maxSum), 0);
int right = max(getMaxPathSum(root->right, maxSum), 0);
maxSum = max(maxSum, left+right+root->val);
return max(left, right) + root->val;
}
public:
int maxPathSum(TreeNode* root) {
if(!root) return 0;
int maxSum = INT_MIN;
getMaxPathSum(root, maxSum);
return maxSum;
}
};