Given a Binary Tree with distinct nodes. Given two nodes node1 and node2, check if the two nodes lies in the same subtree of the root node. That is, either of the left and right subtrees of the root node.
For Example: In the above binary tree, node 3 and 8 are in the same subtree but 4 and 5 are in different subtree.
Prerequisite: Check if a node exist in Binary Tree.
The idea is similar of searching a node in Binary Tree. There are four different cases:
- If both node1 and node2 are in left subtree of root node.
- If both node1 and node2 are in right subtree of the root node.
- If node1 is in the left subtree of the root node and node2 is in the right subtree of root node.
- If node1 is in the right subtree of the root node and node2 is in the left subtree of root node.
Use the approach of searching a node in Binary Tree and check if any of the first two cases listed above is True. If any of the first two cases listed above is found True then print YES otherwise print NO.
Below is the implementation of the above approach:
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.