Given a binary tree, print all cousins of a given node. 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


6, 7 are cousins of node 4 or 5
4, 5 are cousins of node 6 or 7

Practice this problem

The idea is to find the level of the given node in the binary tree by doing a preorder traversal on it. Once the level is found, print all nodes present in that level, which is not a sibling of the node or the node itself. Following is the implementation of the above approach in C++, Java, and Python:

C++


Download  Run Code

Output:

4 5

Java


Download  Run Code

Output:

4 5

Python


Download  Run Code

Output:

4 5

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.