方法一:递归法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode xParent = null;
TreeNode yParent = null;
int xDepth = -1;
int yDepth = -2;
public boolean isCousins(TreeNode root, int x, int y) {
getDepthAndParent(root, x, y, 0, null);
return xDepth == yDepth && xParent != yParent;
}
// 辅助函数 获取 x,y 的深度和父节点
public void getDepthAndParent(TreeNode root, int x, int y, int depth, TreeNode parent){
if (root == null) {
return;
}
if (root.val == x) {
xParent = parent;
xDepth = depth;
} else if (root.val == y) {
yParent = parent;
yDepth = depth;
} else {
// 不在同一行时,无需继续递归遍历
getDepthAndParent(root.left, x, y, depth + 1, root);
getDepthAndParent(root.right, x, y, depth + 1, root);
}
}
}
方法二:BFS层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isCousins(TreeNode root, int A, int B) {
if (root == null) return false;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
boolean isAExist = false;
boolean isBExist = false;
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
if (cur.val == A) isAExist = true;
if (cur.val == B) isBExist = true;
if (cur.left != null && cur.right != null) {
if (cur.left.val == A && cur.right.val == B) {
return false;
}
if (cur.left.val == B && cur.right.val == A) {
return false;
}
}
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
if (isAExist && isBExist) return true;
// 如果不在同一行,直接返回 false,无需再继续遍历
if (isAExist || isBExist) return false;
}
return false;
}
}