Are the Two Nodes on the Same Level With Different Parents
Implement areCousins
You are given the root of a binary tree in which all node values are distinct, and two different integers x and y. Two nodes are cousins if they are on the same level of the tree but their parents are different nodes. Return true if the tree contains both x and y and the nodes holding them are cousins; otherwise return false.
You can find each value's depth and parent with two searches, or sweep the tree level by level and decide as soon as you know.
Example 1:
Input: root = [14,6,19,3,9,null,25,null,5,8], x = 3, y = 25
Output: true
Example 2:
Input: root = [14,6,19,3,9,null,25,null,5,8], x = 3, y = 9
Output: false
Example 3:
Input: root = [14,6,19,3,9,null,25,null,5,8], x = 5, y = 25
Output: false
+ 13 hidden test cases run on Submit.
Constraints:
- ●
2 ≤ number of nodes ≤ 100, and every node value is distinct, 1 ≤ node.val ≤ 1000 - ●
x and y are two different integers between 1 and 1000; they may or may not appear in the tree - ●
The tree is given as its root node; each node has a val, a left child and a right child - ●
Two nodes are "cousins" when they are on the same level (same depth) but have different parents. Return true if both x and y are in the tree and their nodes are cousins; otherwise false (siblings, different levels, or a missing value)
root =
x =
y =