Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.
Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7
Note that it is the same problem as given at Print cousins of a given node in Binary Tree which consists of two traversals recursively. In this post, a single level traversal approach is discussed.
The idea is to go for level order traversal of the tree, as the cousins and siblings of a node can be found in its level order traversal. Run the traversal till the level containing the node is not found, and if found, print the given level.
How to print the cousin nodes instead of siblings and how to get the nodes of that level in the queue? During the level order, when for the parent node, if parent->left == Node_to_find, or parent->right == Node_to_find, then the children of this parent must not be pushed into the queue (as one is the node and other will be its sibling). Push the remaining nodes at the same level in the queue and then exit the loop. The current queue will have the nodes at the next level (the level of the node being searched, except the node and its sibling). Now, print the queue.
Following is the implementation of the above algorithm.
Node not found Cousin Nodes : None Cousin Nodes : None Cousin Nodes : None Cousin Nodes : 6 7
Time Complexity : This is a single level order traversal, hence time complexity = O(n), and Auxiliary space = O(n) (See this).
- Print cousins of a given node in Binary Tree
- Sum of cousins of a given node in a Binary Tree
- Kth node in Diagonal Traversal of Binary Tree
- Find n-th node in Preorder traversal of a Binary Tree
- Find n-th node in Postorder traversal of a Binary Tree
- Find the kth node in vertical order traversal of a Binary Tree
- Print Ancestors of a given node in Binary Tree
- Print the number of set bits in each node of a Binary Tree
- Print path from root to a given node in a binary tree
- Print the nodes of binary tree as they become the leaf node
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check if two nodes are cousins in a Binary Tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Zig Zag Level order traversal of a tree using single queue
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Rajput-Ji