Cousins in Binary Tree LeetCode solution in JavaScript

1
var isCousins = function (root, x, y) {
2
let xHeight = 1;
3
let xParent = null;
4
let yHeight = 1;
5
let yParent = null;
6

7
const helper = (node, depth, parent) => {
8
if (node === null) return null;
9

10
helper(node.left, depth + 1, node);
11
helper(node.right, depth + 1, node);
12

13
let val = node.val;
14

15
if (val === x) {
16
xHeight = depth;
17
xParent = parent;
18
}
19

20
if (val === y) {
21
yHeight = depth;
22
yParent = parent;
23
}
24
};
25

26
helper(root, 0);
27

28
return xHeight === yHeight && xParent !== yParent ? true : false;
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0