Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees.
Input : Roots of below trees 10 10 / \ / 5 6 5 Output : false Input : Roots of below trees 10 10 / \ / \ 5 6 5 6 Output : true
We have discussed recursive solution here. In this article iterative solution is discussed.
The idea is to use level order traversal. We traverse both trees simultaneously and compare the data whenever we dequeue and item from queue. Below is the implementation of the idea.
Time complexity of above solution is O(n + m) where m and n are number of nodes in two trees.
This article is contributed by Ankur Lathiya .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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Iterative method to check if two trees are mirror of each other
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Write Code to Determine if Two Trees are Identical
- Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
- Check for Symmetric Binary Tree (Iterative Approach)
- Iterative approach to check if a Binary Tree is Perfect
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative approach to check for children sum property in a Binary Tree
- Check if two trees are Mirror
- Check if two trees have same structure
- Check if two trees are Mirror | Set 2
- Check if all levels of two trees are anagrams or not
- Check if leaf traversal of two Binary Trees is same?
- Check if two trees are mirror of each other using level order traversal
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Generic Trees(N-array Trees)
- Find largest subtree having identical left and right subtrees
- Iterative Preorder Traversal
- Iterative Postorder traversal | Set 3