题目描述:
一开始以为是必须经过根节点,因此走了弯路,弄了半天才用递归写出来了,不得不说递归实在是精妙,但是用不好很难受
代码:
/**
* 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) {
getdep(root);
return max;
}
public int getdep(TreeNode root){
if(root == null){
return 0;
}else {
int left = getdep(root.left);
int right = getdep(root.right);
max = Math.max(left + right,max);
return left > right ? left + 1 :right + 1;
}
}
}