Question
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
.
本题难度Hard。
DFS
【题意】
找出binary tree内的最大路径和,可以是任意路径,但是必须至少包含一个节点(The path must contain at least one node and does not need to go through the root.)
【复杂度】
时间 O(N) 空间 O(logN)
【思路】
很明显这道题肯定得由上而下地做(因为它是tree)。这里要注意节点值可以为负数(这也是Hard所在)。我用了“反推法”,就是先列出答案的各种可能,然后再反推出算法。答案无非有以下几种【图1】:
-1 / \ 2 -3
这种情况路径只含有leaf节点2
-1 / \ -2 -3
这种情况路径就是根节点-1
1 / \ 2 3 / \ / \ -2 -3 -2 -3
这种情况路径就是 2->1->3
看出端倪来了吧,如果有正节点,那么就一定不要包含负节点;如果全部都是负节点,那么选出最大的节点作为路径。我们继续观察:
root1 / root2 / \ 左子树 右子树 <- “α区域”
从root1的角度看,root1要想到达 “α区域”就必须通过节点“root2”。那么什么情况下root1值得通过root2去到达“α区域”呢?答案是只有在(root2.val+Math.max(左子树,右子树))>0
时候才值得。因此我们可以确定DFS的返回值代码为:
return (Math.max(left,right)+root.val)>0?Math.max(left,right)+root.val:0;
最后我们还要考虑最大路径不通过顶层根节点的情况【图2】:
-1 / \ 1 -3 / \ / \ 2 -3 -2 -3
这种情况路径就是 2->1
我将Tree抽象为下图:
root / \ 左子树 右子树
对于root而言,如果左子树不值得去,那么左子树返回值为0(右子树也是如此),所以如果路径一定要包含root节点,其最大路径值一定是:左子树返回值+右子树返回值+root.val
。因此只要在每层节点(包括leaf)中,我们都将左子树返回值+右子树返回值+root.val
与结果ans
进行比较,就可以解决图2的问题。
【代码】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int ans=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return ans;
}
private int helper(TreeNode root){
//base case
if(root==null)return 0;
int left=helper(root.left);
int right=helper(root.right);
ans=Math.max(ans,left+right+root.val);
return (Math.max(left,right)+root.val)>0?Math.max(left,right)+root.val:0;
}
}
【Follow up】
这个算法说是DFS,其实本质应该是DP,你觉得呢