思路:在能够遍历所有节点的递归中嵌套对于该节点延伸出的最长路径的计算,然后利用类变量记录下最长路径。由于要计算每个根节点延伸出的最长路径,可以先计算该根节点的左、右节点为起点的最长路径,然后取最长的组合。递归就可以写成计算根节点为起点最长路径的函数,然后递归成左节点为起点,右节点为起点,正好可以遍历所有节点。
/**
* Created by marsares on 15/6/14.
*/
public class BinaryTreeMaximumPathSum {
int maxPath=0;
public int maxPathSum(TreeNode root) {
maxPath=root.val;
maxPathFromP(root);
return maxPath;
}
public int maxPathFromP(TreeNode root){
if(root==null)return 0;
int left=maxPathFromP(root.left);
int right=maxPathFromP(root.right);
int val=max(root.val+left+right,max(root.val,max(root.val+left,root.val+right)));
if(val>maxPath)maxPath=val;
return max(root.val,max(root.val+left,root.val+right));
}
private int max(int a,int b){
return (a>b)?a:b;
}
public static void main(String[]args){
BinaryTreeMaximumPathSum btmp=new BinaryTreeMaximumPathSum();
BinaryTreeSerialize bts=new BinaryTreeSerialize();
TreeNode root=bts.Unserialize("{1,2,3,4,5,6,7,8,9}");
System.out.println(btmp.maxPathSum(root));
}
}