Leetcode 993. Cousins in Binary Tree Sure, let’s go through this problem step-by-step.
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth but have different parents.
Given the root of a binary tree with unique values and the values x and y of two different nodes in the tree, return true if and only if the nodes corresponding to the values x and y are cousins.
x and y be equal?
x or y is not found in the tree?
false.x and y exist in the tree?
false.x and y, we check their depths and parents to decide if they are cousins.import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public boolean isCousins(TreeNode root, int x, int y) {
if (root == null) {
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
TreeNode xParent = null, yParent = null;
int xDepth = -1, yDepth = -1;
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
if (node.left.val == x) {
xParent = node;
xDepth = depth + 1;
} else if (node.left.val == y) {
yParent = node;
yDepth = depth + 1;
}
}
if (node.right != null) {
queue.offer(node.right);
if (node.right.val == x) {
xParent = node;
xDepth = depth + 1;
} else if (node.right.val == y) {
yParent = node;
yDepth = depth + 1;
}
}
}
depth++;
}
// Check if x and y are cousins
return xDepth == yDepth && xParent != yParent;
}
}
n is the number of nodes in the tree.n/2 nodes.Let me know if there’s anything you need further clarification on!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?