题目:
算法思想:
我们之前学过如何求树的最大深度,这题起始就是求每个结点左右子树的最大深度,他们的和即为直径。
代码:
class Solution {
int res = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null) {
return 0;
}
int left = height(root.left);
int right = height(root.right);
diameterOfBinaryTree(root.left);
diameterOfBinaryTree(root.right);
res = Math.max(left + right, res);
return res;
}
public int height(TreeNode root) {
if(root == null) {
return 0;
}
int left = height(root.left);
int right = height(root.right);
return Math.max(left, right) + 1;
}
}



