思路:二叉树中的最大路径和,采用后序遍历,自底向上。
int max=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root){
if(root==null) return 0;
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root==null) return 0;
int left=Math.max(0,dfs(root.left));//左孩子的贡献
int right=Math.max(0,dfs(root.right));//右孩子的贡献
max=Math.max(max,root.val+left+right);//更新当前结点作为根结点时的二叉树内部最大路径
return root.val+Math.max(left,right);//当前结点的贡献
}