Cousins In Binary Tree

How to check if two nodes are cousins in a Binary tree.

Given two values x and y, we have to write a code to check the nodes corresponding to values x and y are cousins or not. All the values in this binary tree are unique.

Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

For example – You can check the image below

Example 1-

In this first example the value of x is 4 and y is 3. The parent of both the nodes are different and but they don’t have same depth.

They are not cousins so we return false.

Example 2-

X = 5, Y = 4

The parent of both the nodes are different and also they have same depth. Both the nodes of a binary tree are cousins. We return true.

Example 3-

X = 2, Y = 3

Both the nodes have same parent. They are not cousins, so we return false.

Let’s discuss multiple approaches to solve this problem.

Data Structure Video Tutorials

Programming Questions on Arrays

Programming Questions on Linked List

Check If Two Nodes are Cousins in a Binary Tree using Level Order Traversal – Java Code

In this example, we check if two nodes are cousins in a binary tree using Breadth First Search (BFS).

Traverse a binary tree level by level. Then, put it’s parent node value and level in two different HashMap. Once the traversal is complete we can check whether two nodes have same depth and different parents.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Cousins In Binary Tree using Depth First Search (DFS) – Java Code

The another way to solve this problem is to use Depth First Search to find the depth and level of both the nodes. Then check if both the nodes have same depth and different parents.

The time complexity of this approach is O(n).

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.