Iterative function to check if two trees are identical
- Difficulty Level : Easy
- Last Updated : 17 Jul, 2022
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.
Space complexity: O(n) space for queue
This article is contributed by Ankur Lathiya .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. 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.