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
给出一个二叉树,让输出里面节点路径的最大和,路径可以不包括root,但是必须至少含一个节点
思路:
参照大神的解法
每访问一个节点,记下它自身+left + right的值
然后返回它自身+左右子树中较大的和(只能是左右子树中的一个)
因为返回到上一层的时候,比如example 2的20->15->7的子树,返回到上一层的和只能是20+15或20+7,而不能是20+15+7,那样如果包含-10这个点,就不能算作一个路径了
然后因为之前保存过它自身+left + right的值,所以选这两者中较大的即可找出最大和路径
然后左右子树可以不选,不选即返回0,即返回max(0, left_sum)
//1ms
class Example {
int ans = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
maxSum(root);
return ans;
}
public int maxSum(TreeNode root) {
if (root == null) {
return 0;
}
int left = Math.max(0, maxSum(root.left));
int right = Math.max(0, maxSum(root.right));
//each time save the max value..
ans = Math.max(ans, left + right + root.val);
//when return to above level, only one of left and right..
return Math.max(left, right) + root.val;
}
}