Given the binary Tree and the two nodes say ‘a’ and ‘b’, determine whether the two nodes are cousins of each other or not.
Two nodes are cousins of each other if they are at same level and have different parents.
6 / \ 3 5 / \ / \ 7 8 1 3 Say two node be 7 and 1, result is TRUE. Say two nodes are 3 and 5, result is FALSE. Say two nodes are 7 and 5, result is FALSE.
The idea is to find level of one of the nodes. Using the found level, check if ‘a’ and ‘b’ are at this level. If ‘a’ and ‘b’ are at given level, then finally check if they are not children of same parent.
Following is the implementation of the above approach.
Time Complexity of the above solution is O(n) as it does at most three traversals of binary tree.
This article is contributed by Ayush Srivastava. 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.
- Check if two nodes are cousins in a Binary Tree | Set-2
- Sum of cousins of a given node in a Binary Tree
- Print cousins of a given node in Binary Tree
- Print cousins of a given node in Binary Tree | Single Traversal
- Check if two nodes in a Binary Tree are siblings
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- Check sum of Covered and Uncovered nodes of Binary Tree
- Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Sum of all nodes in a binary tree
- Sum of all nodes at Kth level in a Binary Tree
- Sum of nodes in the right view of the given binary tree
- XOR of path between any two nodes in a Binary Tree
- Sink Odd nodes in Binary Tree
- Sink even nodes in Binary Tree
- Sum of all leaf nodes of binary tree
- Product of all nodes in a Binary Tree
- Sum of nodes in top view of binary tree