1 解题思想
在二叉树当中,找到一条路径,这条路径的和最大。
这里所谓的路径,就是每个节点只经过一次的一条路径,可以选择在任何节点开始,也可以选择在任何节点结束
本质上,其有点像用DP的递归方式搜索,因为每个节点只能经过一次,所以对于当前root,最大值可能是:
- root当前值,左右孩子的值,一共三个值,所有大于0的值的和
但是当 当前root回溯回去,到了其父节点时,root能返回的最值至多包含一个子节点的值。。
嗯,上面可能有些拗口,看代码去吧。。。哈哈,我也讲不清楚。。看着代码好讲些
2 原题
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
Return 6.
3 AC解
/**
* 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 globalMax = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return globalMax;
}
/**
* 因为这道题的要求是一个可以到达的路径(图像化理解为:从一边上来,到了最高处后,往下转过去,又是一条折线)也就是说除了某一个节点的位置之外(也就是当前序列深度最小的那一个),其余的位置节点,只能留自己孩子节点里面-》左边或者右边的一个,所以每次需要判断如果当前节点是深度最低的那个,或者自己只是作为其中的一部分,还有更低的节点
*/
public int helper(TreeNode root) {
int leftMax = root.left==null?Integer.MIN_VALUE:helper(root.left);
int rightMax = root.right==null?Integer.MIN_VALUE:helper(root.right);
// 如果当前位置为转折
int res = root.val;
if(leftMax > 0) res += leftMax;
if(rightMax > 0) res += rightMax;
globalMax = Math.max(globalMax,res);
// 如果自己只是作为其中一部分
return root.val + Math.max(Math.max(0,leftMax),rightMax);
}
}
最近频繁发生因为leetcode题目测试数据变动而造成的代码不能AC,所以这里特别贴出AC
因为代码完成时间长短不定,所以如果我给的代码不能AC了,请及时评论通知我,我会及时修改的