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
寻找和最大的树的路径,树的路径不应该同时包括两个左叶子节点或者两个右叶子节点。使用递归的方法找到当前根节点的路径最大值,每次找到(当前根节点值、当前根节点加左右子树节点最大值、当前根节点和左子树最大值、当前根节点和右子树最大值)的最大值赋给全局变量max,每个子树的路径最大值不是当前节点和左右子树相加的值,而是(当前节点、当前节点加左子树、当前节点加右子树)的最大值,因为是路径。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class num124 {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
rootSum(root);
return max;
}
public int rootSum(TreeNode root){
if(root == null) return 0;
int ls = rootSum(root.left);
int rs = rootSum(root.right);
this.max = Math.max(max, root.val + ls + rs);
this.max = Math.max(max, root.val);
int leftAcur = root.val + ls;
int rightAcur = root.val + rs;
this.max = Math.max(max, leftAcur);
this.max = Math.max(max, rightAcur);
if(leftAcur < 0 && rightAcur < 0){
return root.val < 0 ? 0 : root.val;
}
return leftAcur > rightAcur? leftAcur : rightAcur;
}
}