给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int res=0;
public int diameterOfBinaryTree(TreeNode root) {
count(root);
return res;
}
public int count(TreeNode root){
if(root==null) return 0;
int l=count(root.left);
int r=count(root.right);
res = Math.max(res,l+r);
return Math.max(l,r)+1;
}
}