Given a binary tree and two nodes, the task is to check if the nodes are siblings of each other or not.
Two nodes are said to be siblings if they are present at the same level, and their parents are same.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 First node is 4 and Second node is 6. Output : No, they are not siblings. Input : 1 / \ 5 6 / / \ 7 3 4 First node is 3 and Second node is 4 Output : Yes
Approach: On observing carefully, it can be concluded that any node in a binary tree can have maximum of two child nodes. So, since the parent of two siblings must be same, so the idea is to simply traverse the tree and for every node check if the two given nodes are it’s children. If it is true for any node in the tree then print YES otherwise print NO.
Below is the implementation of the above approach:
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.
- Find the maximum GCD of the siblings of a Binary Tree
- Check if two nodes are cousins in a Binary Tree
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check sum of Covered and Uncovered nodes of Binary Tree
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- 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
- Number of siblings of a given Node in n-ary Tree
- Sum of all nodes in a binary tree
- Sum of all nodes at Kth level in a Binary Tree
- Sink even nodes in Binary Tree
- Sum of nodes in the right view of the given binary tree
- Sum of nodes in top view of binary tree
- Sum of all the Boundary Nodes of a Binary Tree
- Sink Odd nodes in Binary Tree
- Sum of all leaf nodes of binary tree
- Product of all nodes in a Binary Tree
- XOR of path between any two nodes in a Binary Tree
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.