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
- Find n-th node in Preorder traversal of a Binary Tree
- Find n-th node in Postorder traversal of a Binary Tree
- Print Ancestors of a given node in Binary Tree
- Print the nodes of binary tree as they become the leaf node
- 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
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check if two nodes are cousins in a 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)
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
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