Given two binary trees. The task is to write a program to check if the two trees are identical in structure.
In the above figure both of the trees, Tree1 and Tree2 are identical in structure. That is, they have the same structure.
Note: This problem is different from Check if two trees are identical as here we need to compare only the structures of the two trees and not the values at their nodes.
The idea is to traverse both trees simultaneously following the same paths and keep checking if a node exists for both the trees or not.
- If both trees are empty then return 1.
- Else If both trees are non-empty:
- Check left subtrees recursively i.e., call isSameStructure(tree1->left_subtree, tree2->left_subtree)
- Check right subtrees recursively i.e., call isSameStructure(tree1->right_subtree, tree2->right_subtree)
- If the value returned in above two steps are true then return 1.
- Else return 0 (one is empty and other is not).
Below is the implementation of above algorithm:
Both trees have same structure
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.
- Check if two trees are Mirror
- Check if two trees are Mirror | Set 2
- Check if all levels of two trees are anagrams or not
- Iterative method to check if two trees are mirror of each other
- Iterative function to check if two trees are identical
- Check if leaf traversal of two Binary Trees is same?
- Check if two trees are mirror of each other using level order traversal
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Generic Trees(N-array Trees)
- B*-Trees implementation in C++
- AA Trees | Set 1 (Introduction)
- Isomorphism in N-ary Trees
- Disjoint Set Union on trees | Set 2
- Disjoint Set Union on trees | Set 1
- Enumeration of Binary Trees
- Dynamic Programming on Trees | Set-1
- Dynamic Programming on Trees | Set 2
- m-WAY Search Trees | Set-1 ( Searching )
- Red-Black Trees | Top-Down Insertion
- DP on Trees | Set-3 ( Diameter of N-ary 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.