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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Print Ancestors of a given node in Binary Tree
- Print path from root to a given node in a binary tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Check whether a given binary tree is skewed binary tree or not?
- 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 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
- Find parent of given node in a Binary Tree with given postorder traversal
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)