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
用Binary
Tree最常用的dfs来进行遍历。先算出左右子树的结果L和R,如果L大于0,那么对 后续结果是有利的,我们加上L,如果R大于0,对后续结果也是有利的,继续加上R
Tree最常用的dfs来进行遍历。先算出左右子树的结果L和R,如果L大于0,那么对 后续结果是有利的,我们加上L,如果R大于0,对后续结果也是有利的,继续加上R
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int maxSum;
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
dfs(root);
return maxSum;
}
private int dfs(TreeNode root) {
if (root == null)
return 0;
int left = dfs(root.left);
int right = dfs(root.right);
int sum = root.val;
if (left > 0)
sum += left;
if (right > 0)
sum += right;
maxSum = Math.max(maxSum, sum);
return Math.max(left, right) > 0 ? Math.max(left, right) +
root.val : root.val;
}
}