二叉树的直径

20 阅读1分钟
// 二叉树的直径  
// 输入:root = [1,2,3,4,5]  
// 输出:3  
// 解释:3 ,取路径 [4,2,1,3] 或 [5,2,1,3] 的长度。  
private static int ans;  
public static int diameterOfBinaryTree(TreeNode root){  
    ans=1;  
    treeDepth(root);  
    return ans-1;  
}  
private static int treeDepth(TreeNode root) {  
    if(root==null) return 0;  
    int l=treeDepth(root.left);  
    int r=treeDepth(root.right);  
    ans=Math.max(ans,l+r+1);  
    return Math.max(l,r)+1;  
}