Given a binary tree, determine if two given nodes are cousins of each other or not. Two nodes of a binary tree are cousins of each other only if they have different parents, but they are at the same level.

For example, consider the following tree:

Level Order Traversal

(4, 6), (4, 7), (5, 6) and (5, 7) are cousins of each other.
(2, 3), (4, 5), (6, 7), (4, 3), etc., are not cousins of each other.

Practice this problem

The idea is to search for given nodes in a binary tree by doing inorder traversal on the tree and store their level and parent node. If both nodes are present at the same level and have different parents, they are cousins. If their level is different, or they are a sibling, they cannot be cousins.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Nodes are cousins of each other

Java


Download  Run Code

Output:

Nodes are cousins of each other

Python


Download  Run Code

Output:

Nodes are cousins of each other

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.