How to Check if Two Nodes are Cousins
In a binary tree, two nodes are considered cousins if they are at the same level but do not share the same parent. Identifying whether two nodes are cousins can be a challenging task, especially when dealing with large and complex trees. This article will guide you through the process of checking if two nodes are cousins in a binary tree.
Understanding the Problem
Before diving into the solution, it is essential to understand the problem’s requirements. Given a binary tree and two nodes, we need to determine if they are cousins. The binary tree is represented using nodes, where each node has a value, a left child, and a right child. The nodes can be empty (represented by null), and the tree can be empty as well.
Approach
To check if two nodes are cousins, we can use a breadth-first search (BFS) algorithm. BFS traverses the tree level by level, allowing us to compare the levels of the two nodes. Here’s a step-by-step approach:
1. Start by initializing a queue and enqueue the root node.
2. Enqueue the values of the two nodes whose cousin status we want to check.
3. Set a flag to indicate whether the nodes have been found at the same level.
4. While the queue is not empty, perform the following steps:
a. Dequeue a node from the queue.
b. Check if the node’s value matches either of the two nodes we’re checking for. If so, set the flag to true.
c. Enqueue the left and right children of the current node, if they exist.
5. After the BFS traversal, if the flag is true, the two nodes are cousins; otherwise, they are not.
Implementation
Here’s a Python implementation of the approach described above:
“`python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def are_cousins(root, node1, node2):
if not root or not node1 or not node2:
return False
queue = [(root, 0)]
node1_level = node2_level = -1
while queue:
current_node, level = queue.pop(0)
if current_node.value == node1.value:
node1_level = level
if current_node.value == node2.value:
node2_level = level
if node1_level != -1 and node2_level != -1:
return node1_level == node2_level
if current_node.left:
queue.append((current_node.left, level + 1))
if current_node.right:
queue.append((current_node.right, level + 1))
return False
“`
Conclusion
In this article, we discussed how to check if two nodes are cousins in a binary tree. By using a breadth-first search algorithm, we can determine if two nodes are at the same level but do not share the same parent. The provided Python implementation can be used as a reference for solving similar problems in binary trees.