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
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 leaf traversal of two Binary Trees is same?
- Generic Trees(N-array Trees)
- Iterative function to check if two trees are identical
- Iterative method to check if two trees are mirror of each other
- Check if two trees are Mirror | Set 2
- 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
- Check if two trees are Mirror
- Check if all levels of two trees are anagrams or not
- Number of distinct pair of edges such that it partitions both trees into same subsets of nodes
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Check if two nodes are in same subtree of the root node
- Check if two nodes are on same path in a tree | Set 2
- Write Code to Determine if Two Trees are Identical
- Print Common Nodes in Two Binary Search Trees
- Find first non matching leaves in two binary trees
- Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
- Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal
- Construct a Maximum Binary Tree from two given Binary Trees
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.