Easy
跟之前做过的有一道题很像,也是用height() method写,但是并不是返回height, 只是在求height的过程中更新了需要求的那个变量
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
if (root == null){
return 0;
}
height(root);
return max;
}
private int height(TreeNode root){
if (root == null){
return -1;
}
int left = height(root.left);
int right = height(root.right);
max = Math.max(max, left + right + 2);
return Math.max(left, right) + 1;
}
}