class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
return depth(root,x)==depth(root,y)&&father(root,x)!=father(root,y);
}
int depth(TreeNode root,int x) {
if(root==null)
return -100;
else {
TreeNode L=root.left,R=root.right;
if(root.val==x)
return 1;
else
return Math.max(depth(L,x)+1, depth(R,x)+1);
}
}
TreeNode father(TreeNode root,int x) {
if(root==null)
return null;
else {
TreeNode L=root.left,R=root.right;
if((L!=null&&L.val==x)||(R!=null&&R.val==x))
return root;
else {
if(father(L,x)!=null)
return father(L,x);
if(father(R,x)!=null)
return father(R,x);
}
}
return null;
}
}
3ms,beats 100%