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.
Input: root = [1,2,3,4], x = 4, y = 3
Output: False
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: True
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: False
x and y?x and y are unique integers that are guaranteed to be in the tree.To determine if two nodes are cousins, we need to ensure:
We can accomplish this using a Breadth-First Search (BFS) approach:
x and y, we compare their depths and parents.from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isCousins(root, x, y):
if not root:
return False
queue = deque([(root, None, 0)]) # node, parent, depth
x_info = y_info = None
while queue:
node, parent, depth = queue.popleft()
if node.val == x:
x_info = (parent, depth)
if node.val == y:
y_info = (parent, depth)
if x_info and y_info:
break
if node.left:
queue.append((node.left, node, depth + 1))
if node.right:
queue.append((node.right, node, depth + 1))
if x_info and y_info:
return x_info[1] == y_info[1] and x_info[0] != y_info[0]
return False
x or y, we note its parent and depth.x and y are found, we compare their depths and parents to determine if they are cousins.True. Otherwise, we return False.This approach ensures that we efficiently determine whether two nodes are cousins by leveraging BFS to capture their depth and parent information.
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?