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.
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.
- Write Code to Determine if Two Trees are Identical
- Iterative method to check if two trees are mirror of each other
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
- Generic Trees(N-array Trees)
- Find largest subtree having identical left and right subtrees
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Check if leaf traversal of two Binary Trees is same?
- Check if two trees are Mirror
- Check if all levels of two trees are anagrams or not
- Check if two trees are Mirror | Set 2
- Check if two trees are mirror of each other using level order traversal
- Check if two trees have same structure
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Check for Symmetric Binary Tree (Iterative Approach)
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative approach to check if a Binary Tree is Perfect
- Iterative approach to check for children sum property in a Binary Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Print Common Nodes in Two Binary Search Trees