题目: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.
思路:首先我们分析一下对于指定某个节点为根时,最大的路径和有可能是哪些情况。一共有4中情况,第一种左子树的路径加上当前节点;第二种,右子树的路径加上当前节点;第三种,左右子树的路径加上当前节点(相当于一条横跨当前节点的路径);第四种,只有自己的路径。这四种情况只是用来计算以当前节点根的最大路径,如果当前节点上面还有节点,那它的父节点是不能累加第三种情况的,所以我们要计算两个最大值,一个是当前节点下最大路径和,另一个是如果要连接父节点时最大的路径和。我们用前者更新全局最大量,用后者返回递归值就行了。
其中左右子树的最大路径和:贪心来做,状态转移方程为
maxSum(*root)=max(root->val, root->val+max(maxSum(*root->left), maxSum(*root->right))).
代码1:
class Solution {
public:
int help(TreeNode* root, int &re){//以该节点为根节点的最大路径和
if (!root) return 0;
int l=max(0, help(root->left, re));
int r=max(0, help(root->right, re));
//当前节点的最大路径是一、二、三、四这四种情况的最大值
re = max(re, root->val+l+r);
//连接父节点的最大路径是一、二、四这三种情况的最大值
return max(root->val, root->val+max(l, r));
}
int re;
int maxPathSum(TreeNode* root) {
int re=INT_MIN;
help(root, re);
return re;
}
};
代码2:
public class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return max;
}
public int helper(TreeNode root) {
if(root == null) return 0;
int left = helper(root.left);
int right = helper(root.right);
//连接父节点的最大路径是一、二、四这三种情况的最大值
int currSum = Math.max(Math.max(left + root.val, right + root.val), root.val);
//当前节点的最大路径是一、二、三、四这四种情况的最大值
int currMax = Math.max(currSum, left + right + root.val);
//用当前最大来更新全局最大
max = Math.max(currMax, max);
return currSum;
}
}
reference:https://blog.youkuaiyun.com/mmwwxx123/article/details/81867450