Leetcode 993
5.17的每日一题993. 二叉树的堂兄弟节点
同深度 , 不同父节点 就可判断
直接dfs查找,若不存在,返回null
不在第n层就继续往下走
public class isCousins993 {
TreeNode parX;
TreeNode parY;
int deepX;
int deepY;
public boolean isCousins(TreeNode root, int x, int y) {
dfs(root, null, 0, x, y);
return parX != parY && deepX == deepY;
}
private void dfs(TreeNode root, TreeNode par, int deep, int x, int y) {
if (root == null)
return;
if (root.val == x) {
deepX = deep;
parX = par;
} else if (root.val == y) {
deepY = deep;
parY = par;
} else {
dfs(root.left, root, deep + 1, x, y);
dfs(root.right, root, deep + 1, x, y);
}
}
}