【DFS】DFS的过程中记录父节点和层数即可。
class Solution {
int[] xx, yy;
public void dfs(TreeNode root, int x, int y, int d, int f) {
if (root.val == x) xx = new int[] {d, f};
if (root.val == y) yy = new int[] {d, f};
if (root.left != null) dfs(root.left, x, y, d + 1, root.val);
if (root.right != null) dfs(root.right, x, y, d + 1, root.val);
}
public boolean isCousins(TreeNode root, int x, int y) {
dfs(root, x, y, 0, -1);
return xx[0] == yy[0] && xx[1] != yy[1];
}
}