welcome to my blog
LeetCode Top 100 Liked Questions 124. Binary Tree Maximum Path Sum (Java版; Hard)
题目描述
Given a non-empty 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.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
core(root);
return max;
}
private int core(TreeNode root){
if(root==null){
return 0;
}
int L = core(root.left);
int R = core(root.right);
max = Math.max(max, root.val + Math.max(0, L) + Math.max(0, R));
return root.val + Math.max(0, Math.max(L, R));
}
}
第一次做; 核心: 弄清楚递归函数的返回值是什么? 递归函数的中间过程在做什么? 递归函数的中间过程并不都是为返回值服务的! 本题就是, 有一部分中间过程为了更新全局变量max, 返回值需要从另一个角度考虑! 在脑子里过一下注释中的两个绊脚案例
/*
核心: 每一次递归时, 计算以当前root(当前条件)作为媒介的结果, 如果比全局变量max大就更新max,如果不比全局max大就不更新
绊脚案例
[-3]
[-2,-1]
*/
class Solution {
public int maxPathSum(TreeNode root) {
//题目说了给出的是非空二叉树, 也就不用进行input check了
max = Integer.MIN_VALUE;
int res = Core(root);
return max;
}
public static int max = Integer.MIN_VALUE;
/*
递归逻辑:计算以当前root(当前条件)作为中间节点的结果,也就是root.val+左子树(新条件新递归)的结果+右子树(新条件新递归)的结果, 根据结果和max的大小决定是否更新全局变量max, 返回以root为端点的最长路径
易错点: 返回值并不是root.val+左子树的结果+右子树的结果; 而是root.val+max(0, max(左子树的结果, 右子树的结果)); 因为路径只有两个端点, 不能有多个端点
*/
public static int Core(TreeNode root){
//base case
if(root==null)
return 0;//0表示null对最终结果没有贡献
//以root.left为根(新条件新递归)的二叉树的结果; 起初我是卡在sum是否变化上了
int left = Core(root.left);
//以root.right为根(新条件新递归)的二叉树的结果
int right = Core(root.right);
//以root为媒介,连接左子树的路径和右子树的路径
int curr = root.val + Math.max(0, left) + Math.max(0, right) ;
//看看是否需要更新最大值
max = Math.max(max, curr);
//
return root.val + Math.max(Math.max(0,left), Math.max(0,right));
}
}