题目描述
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return6.
import java.util.*;
public class binary_tree_maxPathSum {
static int max_val=0;
public static void main(String[] args) {
TreeNode a= new TreeNode(1);
TreeNode b= new TreeNode(-2);
TreeNode c= new TreeNode(3);
a.left=b;
a.right=c;
max_val=Integer.MIN_VALUE;
maxPathSum(a);
System.out.println(max_val);
}
public static int maxPathSum(TreeNode root) {
if(root==null) {
return 0;
}
// 左子树最大路径 (小于0 则为0)
int l=Math.max(0, maxPathSum(root.left)) ;
// 右子树最大路径(小于0 则为0)
int r=Math.max(0, maxPathSum(root.right)) ;
// 以当前节点作为根节点,则最大路径为 左+右+根
max_val=Math.max(max_val,l+r+root.val );
// 作为上一层节点的左/右子树 返回值 只能是左+根 \ 右+根 中最大的
return Math.max(0, root.val+Math.max(l, r));
}
}