2
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode3
* right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,4
* TreeNode right) { this.val = val; this.left = left; this.right = right; } }7
public boolean isCousins(TreeNode root, int x, int y) {9
// If any of x or y is at root, it means they can't be at same depth. Return false.10
if (root.val == x || root.val == y) return false;12
Deque<TreeNode> queue = new LinkedList<>();15
boolean xFound = false;16
boolean yFound = false;21
// Do level-order traversal until x or y is found or queue is empty.22
while (!queue.isEmpty() && !xFound && !yFound) {24
int size = queue.size();26
// Traverse that level.28
TreeNode node = queue.poll();30
// if x or y is found at left/right, save the parent and set the "found" flag to true.31
// This flag will break the loop as soon as any one (x or y) is found.32
// we don't need to go deeper to find second if it isn't found at this level.34
if (node.left != null) {35
queue.offer(node.left);37
if (node.left.val == x) {41
if (node.left.val == y) {47
if (node.right != null) {48
queue.offer(node.right);50
if (node.right.val == x) {54
if (node.right.val == y) {61
return xFound && yFound && parentX != parentY;