题目
代码
class Solution {
int ans = 1;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return ans-1;
}
public int depth(TreeNode node) {
if (node == null) return 0;
// 获取左孩子为根的树的深度
int leftDept = depth(node.left);
// 获取右孩子为根的树的深度
int rightDept = depth(node.right);
// leftDept+rihtDept+1表示以node为根时二叉树的最大直径
ans = Math.max(ans,leftDept+rightDept+1);
// 返回以node为根生成树的深度
return Math.max(leftDept,rightDept)+1;
}
}