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
The idea to first find level of given node using the approach discussed here. Once we have found level, we can print all nodes at a given level using the approach discussed here. The only thing to take care of is, sibling should not be printed. To handle this, we change the printing function to first check for sibling and print node only if it is not sibling.
Below is the implementation of above idea.
Time Complexity : O(n)
Can we solve this problem using single traversal? Please refer below article
Print cousins of a given node in Binary Tree | Single Traversal
This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print cousins of a given node in Binary Tree | Single Traversal
- Check if two nodes are cousins in a Binary Tree
- Check if two nodes are cousins in a Binary Tree | Set-2
- Print Ancestors of a given node in Binary Tree
- Print path from root to a given node in a binary tree
- Print the number of set bits in each node of a Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Kth ancestor of a node in binary tree | Set 2
- Search a node in Binary Tree
- K-th ancestor of a node in Binary Tree | Set 3
- Get Level of a node in a Binary Tree
- K-th ancestor of a node in Binary Tree
- Get maximum left node in binary tree
- Kth node in Diagonal Traversal of Binary Tree
- Total sum except adjacent of a given node in a Binary Tree
- Inorder Successor of a node in Binary Tree