思路:二叉树的直径=根结点的左右子树高度相加
注意:不能直接计算dfs(root.left)+dfs(root.right),因为这样是默认这条直径一定经过根结点。
int max=0;
public int diameterOfBinaryTree(TreeNode root) {
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root==null) return 0;
int left=dfs(root.left);
int right=dfs(root.right);
max=Math.max(max,left+right);//求直径
return Math.max(left,right)+1;//求高度
}