Cousins in Binary Tree
Problem statement
Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.
Example 1:

Input: root = [1,2,3,4], x = 4, y = 3Output: false
Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4Output: true
Example 3:

Input: root = [1,2,3,null,4], x = 2, y = 3Output: false
Constraints:
- The number of nodes in the tree is in the range
[2, 100]. 1 <= Node.val <= 100- Each node has a unique value.
x != yxandyare exist in the tree.
My solution
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} x
* @param {number} y
* @return {boolean}
*/
var isCousins = function(root, x, y) {
// return dfs(root, x, y)
return bfs(root, x, y)
};
function bfs(root, x, y) {
if (x === root.val || y === root.val || !root) {
return false
}
let parentX, depthX, parentY, depthY;
const queue = [{
node: root,
depth: 0
}]
while (queue.length) {
let {node, depth} = queue.shift();
if (node.left) {
queue.push({
node: node.left,
depth: depth + 1
})
if (node.left.val === x) {
parentX = node.val
depthX = depth
}
if (node.left.val === y) {
parentY = node.val
depthY = depth
}
}
if (node.right) {
queue.push({
node: node.right,
depth: depth + 1
})
if (node.right.val === x) {
parentX = node.val
depthX = depth
}
if (node.right.val === y) {
parentY = node.val
depthY = depth
}
}
if (parentX && depthX && parentY && depthY) {
break
}
}
return parentX !== parentY && depthX === depthY
}
function dfs(root, x, y) {
if (x === root.val || y === root.val || !root) {
return false
}
const [parentX, depthX] = traverse(root, x, 0)
const [parentY, depthY] = traverse(root, y, 0)
return parentX !== parentY && depthX === depthY
function traverse(node, target, depth) {
if (!node) {
return
}
if (node.left && node.left.val === target) {
return [node.val, depth + 1]
}
if (node.right && node.right.val === target) {
return [node.val, depth + 1]
}
return traverse(node.left, target, depth + 1) || traverse(node.right, target, depth + 1)
}
}