124. Binary Tree Maximum Path Sum
题目
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.
解析
- 这一题有点类似一维数组求最大子序列的和,一维最大子序列和从一维的角度判断,这里二叉树有左右子树考虑。help(root)方法的返回值的意思就是求得root节点到该root子孙的任意一节点的最大路径值(注意区别这里root和根节点root,这里root是递归下去的节点)。在这个函数里还比较了以root为路径节点
class Solution_124 {
int sum = INT_MIN;
int help(TreeNode* root)
{
if (!root)
{
return 0;
}
int left = max(0, help(root->left));
int right = max(0, help(root->right));
sum = max(sum, left + right + root->val); //包括当前节点在路径上的最大值
return max(left, right) + root->val; //返回以当前节点为根的路径最大值
}
public:
int maxPathSum(TreeNode *root) { //考虑有负节点情况
if (!root)
{
return 0;
}
help(root);
return sum;
}
};
题目来源