我本来以为只要获取root左右节点的最大深度就行了,但是最后发现题目上说的是,可以不经过root节点,最开始提交也是有四个每通过,我画了图之后才知道,我还要比较每个节点左右节点返回的最大值,再与最后的root左右节点的深度比较。
var diameterOfBinaryTree = function(root) {
if(!root)return 0;
let num = 0;
let ans = get(root.left) + get(root.right);
function get(root){
if(!root)return 0;
let left = get(root.left);
let right = get(root.right)
num = Math.max(num,left+right);
return Math.max(left,right)+1;
}
ans = Math.max(ans,num);
return ans;
};