Iterative function to check if two trees are identical
Last Updated : 21 Apr, 2025
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. Examples:
Input: Roots of below trees
Output: false
Input: Roots of below trees
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.
C++
/* Iterative C++ program to check if two */#include<bits/stdc++.h>usingnamespacestd;// A Binary Tree NodestructNode{intdata;structNode*left,*right;};// Iterative method to find height of Binary TreeboolareIdentical(Node*root1,Node*root2){// Return true if both trees are emptyif(root1==NULL&&root2==NULL)returntrue;// Return false if one is empty and other is notif(root1==NULL)returnfalse;if(root2==NULL)returnfalse;// Create an empty queues for simultaneous traversals queue<Node*>q1,q2;// Enqueue Roots of trees in respective queuesq1.push(root1);q2.push(root2);while(!q1.empty()&&!q2.empty()){// Get front nodes and compare themNode*n1=q1.front();Node*n2=q2.front();if(n1->data!=n2->data)returnfalse;// Remove front nodes from queuesq1.pop(),q2.pop();/* Enqueue left children of both nodes */if(n1->left&&n2->left){q1.push(n1->left);q2.push(n2->left);}// If one left child is empty and other is notelseif(n1->left||n2->left)returnfalse;// Right child code (Similar to left child code)if(n1->right&&n2->right){q1.push(n1->right);q2.push(n2->right);}elseif(n1->right||n2->right)returnfalse;}returntrue;}// Utility function to create a new tree nodeNode*newNode(intdata){Node*temp=newNode;temp->data=data;temp->left=temp->right=NULL;returntemp;}// Driver program to test above functionsintmain(){Node*root1=newNode(1);root1->left=newNode(2);root1->right=newNode(3);root1->left->left=newNode(4);root1->left->right=newNode(5);Node*root2=newNode(1);root2->left=newNode(2);root2->right=newNode(3);root2->left->left=newNode(4);root2->left->right=newNode(5);areIdentical(root1,root2)?cout<<"Yes":cout<<"No";return0;}
Java
/* Iterative Java program to check if two */importjava.util.*;classGfG{// A Binary Tree Node staticclassNode{intdata;Nodeleft,right;}// Iterative method to find height of Binary Tree staticbooleanareIdentical(Noderoot1,Noderoot2){// Return true if both trees are empty if(root1==null&&root2==null)returntrue;// Return false if one is empty and other is not if(root1==null||root2==null)returnfalse;// Create an empty queues for simultaneous traversals Queue<Node>q1=newLinkedList<Node>();Queue<Node>q2=newLinkedList<Node>();// Enqueue Roots of trees in respective queues q1.add(root1);q2.add(root2);while(!q1.isEmpty()&&!q2.isEmpty()){// Get front nodes and compare them Noden1=q1.peek();Noden2=q2.peek();if(n1.data!=n2.data)returnfalse;// Remove front nodes from queues q1.remove();q2.remove();/* Enqueue left children of both nodes */if(n1.left!=null&&n2.left!=null){q1.add(n1.left);q2.add(n2.left);}// If one left child is empty and other is not elseif(n1.left!=null||n2.left!=null)returnfalse;// Right child code (Similar to left child code) if(n1.right!=null&&n2.right!=null){q1.add(n1.right);q2.add(n2.right);}elseif(n1.right!=null||n2.right!=null)returnfalse;}returntrue;}// Utility function to create a new tree node staticNodenewNode(intdata){Nodetemp=newNode();temp.data=data;temp.left=null;temp.right=null;returntemp;}// Driver program to test above functions publicstaticvoidmain(String[]args){Noderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);Noderoot2=newNode(1);root2.left=newNode(2);root2.right=newNode(3);root2.left.left=newNode(4);root2.left.right=newNode(5);if(areIdentical(root1,root2)==true)System.out.println("Yes");elseSystem.out.println("No");}}
Python
# Iterative Python3 program to check # if two trees are identicalfromqueueimportQueue# Utility function to create a # new tree node classnewNode:def__init__(self,data):self.data=dataself.left=self.right=None# Iterative method to find height of # Binary Tree defareIdentical(root1,root2):# Return true if both trees are empty if(root1androot2):returnTrue# Return false if one is empty and# other is not if(root1orroot2):returnFalse# Create an empty queues for # simultaneous traversals q1=Queue()q2=Queue()# Enqueue Roots of trees in # respective queues q1.put(root1)q2.put(root2)while(notq1.empty()andnotq2.empty()):# Get front nodes and compare them n1=q1.queue[0]n2=q2.queue[0]if(n1.data!=n2.data):returnFalse# Remove front nodes from queues q1.get()q2.get()# Enqueue left children of both nodes if(n1.leftandn2.left):q1.put(n1.left)q2.put(n2.left)# If one left child is empty and# other is not elif(n1.leftorn2.left):returnFalse# Right child code (Similar to # left child code) if(n1.rightandn2.right):q1.put(n1.right)q2.put(n2.right)elif(n1.rightorn2.right):returnFalsereturnTrue# Driver Codeif__name__=='__main__':root1=newNode(1)root1.left=newNode(2)root1.right=newNode(3)root1.left.left=newNode(4)root1.left.right=newNode(5)root2=newNode(1)root2.left=newNode(2)root2.right=newNode(3)root2.left.left=newNode(4)root2.left.right=newNode(5)ifareIdentical(root1,root2):print("Yes")else:print("No")# This code is contributed by PranchalK
C#
/* Iterative C# program to check if two */usingSystem;usingSystem.Collections.Generic;classGfG{// A Binary Tree Node classNode{publicintdata;publicNodeleft,right;}// Iterative method to find height of Binary Tree staticboolareIdentical(Noderoot1,Noderoot2){// Return true if both trees are empty if(root1==null&&root2==null)returntrue;// Return false if one is empty and other is not if(root1==null||root2==null)returnfalse;// Create an empty queues for // simultaneous traversals Queue<Node>q1=newQueue<Node>();Queue<Node>q2=newQueue<Node>();// Enqueue Roots of trees in respective queues q1.Enqueue(root1);q2.Enqueue(root2);while(q1.Count!=0&&q2.Count!=0){// Get front nodes and compare them Noden1=q1.Peek();Noden2=q2.Peek();if(n1.data!=n2.data)returnfalse;// Remove front nodes from queues q1.Dequeue();q2.Dequeue();/* Enqueue left children of both nodes */if(n1.left!=null&&n2.left!=null){q1.Enqueue(n1.left);q2.Enqueue(n2.left);}// If one left child is empty and other is not elseif(n1.left!=null||n2.left!=null)returnfalse;// Right child code (Similar to left child code) if(n1.right!=null&&n2.right!=null){q1.Enqueue(n1.right);q2.Enqueue(n2.right);}elseif(n1.right!=null||n2.right!=null)returnfalse;}returntrue;}// Utility function to create a new tree node staticNodenewNode(intdata){Nodetemp=newNode();temp.data=data;temp.left=null;temp.right=null;returntemp;}// Driver code publicstaticvoidMain(String[]args){Noderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);Noderoot2=newNode(1);root2.left=newNode(2);root2.right=newNode(3);root2.left.left=newNode(4);root2.left.right=newNode(5);if(areIdentical(root1,root2)==true)Console.WriteLine("Yes");elseConsole.WriteLine("No");}}// This code is contributed by PrinciRaj1992
JavaScript
<script>/* Iterative Javascript program to check if two */// A Binary Tree Node classNode{constructor(){this.data=0;this.left=null;this.right=null;}}// Iterative method to find height of Binary Tree functionareIdentical(root1,root2){// Return true if both trees are empty if(root1==null&&root2==null)returntrue;// Return false if one is empty and other is not if(root1==null||root2==null)returnfalse;// Create an empty queues for // simultaneous traversals varq1=[];varq2=[];// push Roots of trees in respective queues q1.push(root1);q2.push(root2);while(q1.length!=0&&q2.length!=0){// Get front nodes and compare them varn1=q1[0];varn2=q2[0];if(n1.data!=n2.data)returnfalse;// Remove front nodes from queues q1.shift();q2.shift();/* push left children of both nodes */if(n1.left!=null&&n2.left!=null){q1.push(n1.left);q2.push(n2.left);}// If one left child is empty and other is not elseif(n1.left!=null||n2.left!=null)returnfalse;// Right child code (Similar to left child code) if(n1.right!=null&&n2.right!=null){q1.push(n1.right);q2.push(n2.right);}elseif(n1.right!=null||n2.right!=null)returnfalse;}returntrue;}// Utility function to create a new tree node functionnewNode(data){vartemp=newNode();temp.data=data;temp.left=null;temp.right=null;returntemp;}// Driver code varroot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);varroot2=newNode(1);root2.left=newNode(2);root2.right=newNode(3);root2.left.left=newNode(4);root2.left.right=newNode(5);if(areIdentical(root1,root2)==true)document.write("Yes");elsedocument.write("No");</script>
Output
Yes
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 Using Iterative Post-Order Traversal and Two Stacks:
The basic idea behind this approach is to traverse both trees in a postorder fashion iteratively, and compare their nodes one by one. We can use two stacks to do this. We start with pushing the root nodes of both trees onto their respective stacks.
Follow the steps to implement the idea:
we repeat the following steps until both stacks are empty:
Pop the top node from each stack.
Compare the popped nodes. If they are not identical, return false.
Push the right subtree of both nodes (if they exist) onto their respective stacks.
Push the left subtree of both nodes (if they exist) onto their respective stacks.
Below is the implementation of the above approach:
C++
// C++ code to implement Iterative Postorder Traversal using// two stacks#include<iostream>#include<stack>usingnamespacestd;/* A binary tree node */structNode{intdata;Node*left,*right;Node(intx){data=x;left=right=NULL;}};/* Iterative Postorder Traversal to check if two binary * trees are identical */boolisIdentical(Node*r1,Node*r2){stack<Node*>stack1,stack2;// loop until both trees are completely traversedwhile(r1!=NULL||!stack1.empty()||r2!=NULL||!stack2.empty()){// push all left nodes of first tree in stack1while(r1!=NULL){stack1.push(r1);r1=r1->left;}// push all left nodes of second tree in stack2while(r2!=NULL){stack2.push(r2);r2=r2->left;}// if size of both stacks is different, trees are// not identicalif(stack1.size()!=stack2.size())returnfalse;// pop one node from each stack and compare their// datar1=stack1.top();stack1.pop();r2=stack2.top();stack2.pop();if(r1->data!=r2->data)returnfalse;// move to the right of the popped nodesr1=r1->right;r2=r2->right;}// both trees are identicalreturntrue;}/* Driver code */intmain(){// Construct the first treeNode*root1=newNode(1);root1->left=newNode(2);root1->right=newNode(3);root1->left->left=newNode(4);root1->left->right=newNode(5);// Construct the second treeNode*root2=newNode(1);root2->left=newNode(2);root2->right=newNode(3);root2->left->left=newNode(4);root2->left->right=newNode(5);// Check if the trees are identicalif(isIdentical(root1,root2))cout<<"Both trees are identical";elsecout<<"Both trees are not identical";return0;}// This code is contributed by Veerendra_Singh_Rajpoot
Java
importjava.util.Stack;// A Java program to implement Iterative Postorder Traversal using two stacks// A binary tree nodeclassNode{intdata;Nodeleft,right;// ConstructorNode(intx){data=x;left=right=null;}}publicclassIdenticalBinaryTrees{// Iterative Postorder Traversal to check if two binary trees are identicalstaticbooleanisIdentical(Noder1,Noder2){Stack<Node>stack1=newStack<>();Stack<Node>stack2=newStack<>();// loop until both trees are completely traversedwhile(r1!=null||!stack1.empty()||r2!=null||!stack2.empty()){// push all left nodes of the first tree in stack1while(r1!=null){stack1.push(r1);r1=r1.left;}// push all left nodes of the second tree in stack2while(r2!=null){stack2.push(r2);r2=r2.left;}// if the size of both stacks is different, trees are not identicalif(stack1.size()!=stack2.size())returnfalse;// pop one node from each stack and compare their datar1=stack1.pop();r2=stack2.pop();if(r1.data!=r2.data)returnfalse;// move to the right of the popped nodesr1=r1.right;r2=r2.right;}// both trees are identicalreturntrue;}//Driver codepublicstaticvoidmain(String[]args){// Construct the first treeNoderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);// Construct the second treeNoderoot2=newNode(1);root2.left=newNode(2);root2.right=newNode(3);root2.left.left=newNode(4);root2.left.right=newNode(5);// Check if the trees are identicalif(isIdentical(root1,root2))System.out.println("Both trees are identical");elseSystem.out.println("Both trees are not identical");}}
Python
# Python code to implement Iterative Postorder Traversal using# two stacks# A class representing a node in the binary treeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Iterative Postorder Traversal to check if two binary # trees are identicaldefisIdentical(r1,r2):stack1=[]stack2=[]# Loop until both trees are completely traversedwhiler1orstack1orr2orstack2:# Push all left nodes of the first tree in stack1whiler1:stack1.append(r1)r1=r1.left# Push all left nodes of the second tree in stack2whiler2:stack2.append(r2)r2=r2.left# If size of both stacks is different, trees are not identicaliflen(stack1)!=len(stack2):returnFalse# Pop one node from each stack and compare their datar1=stack1.pop()r2=stack2.pop()ifr1.data!=r2.data:returnFalse# Move to the right of the popped nodesr1=r1.rightr2=r2.right# Both trees are identicalreturnTrue# Driver codeif__name__=='__main__':# Construct the first treeroot1=Node(1)root1.left=Node(2)root1.right=Node(3)root1.left.left=Node(4)root1.left.right=Node(5)# Construct the second treeroot2=Node(1)root2.left=Node(2)root2.right=Node(3)root2.left.left=Node(4)root2.left.right=Node(5)# Check if the trees are identicalifisIdentical(root1,root2):print("Both trees are identical")else:print("Both trees are not identical")
C#
// C# code to implement Iterative Postorder Traversal using// two stacksusingSystem;usingSystem.Collections.Generic;// A binary tree nodeclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classIterativePostorderTraversal{staticboolIsIdentical(Noder1,Noder2){Stack<Node>stack1=newStack<Node>();Stack<Node>stack2=newStack<Node>();// Loop until both trees are completely traversedwhile(r1!=null||stack1.Count>0||r2!=null||stack2.Count>0){// Push all left nodes of the first tree in stack1while(r1!=null){stack1.Push(r1);r1=r1.left;}// Push all left nodes of the second tree in stack2while(r2!=null){stack2.Push(r2);r2=r2.left;}// If the sizes of both stacks are different, trees are not identicalif(stack1.Count!=stack2.Count)returnfalse;// Pop one node from each stack and compare their datar1=stack1.Pop();r2=stack2.Pop();if(r1.data!=r2.data)returnfalse;// Move to the right of the popped nodesr1=r1.right;r2=r2.right;}// Both trees are identicalreturntrue;}// Driver codestaticvoidMain(string[]args){// Construct the first treeNoderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);// Construct the second treeNoderoot2=newNode(1);root2.left=newNode(2);root2.right=newNode(3);root2.left.left=newNode(4);root2.left.right=newNode(5);// Check if the trees are identicalif(IsIdentical(root1,root2))Console.WriteLine("Both trees are identical");elseConsole.WriteLine("Both trees are not identical");}}
JavaScript
// Define a binary tree node structureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to perform iterative postorder traversal and check if two binary trees are identicalfunctionisIdentical(r1,r2){conststack1=[];conststack2=[];// Loop until both trees are completely traversedwhile(r1||stack1.length>0||r2||stack2.length>0){// Push all left nodes of the first tree into stack1while(r1){stack1.push(r1);r1=r1.left;}// Push all left nodes of the second tree into stack2while(r2){stack2.push(r2);r2=r2.left;}// If the sizes of both stacks are different, the trees are not identicalif(stack1.length!==stack2.length)returnfalse;// Pop one node from each stack and compare their datar1=stack1.pop();r2=stack2.pop();if(r1.data!==r2.data)returnfalse;// Move to the right of the popped nodesr1=r1.right;r2=r2.right;}// Both trees are identicalreturntrue;}// Driver codefunctionmain(){// Construct the first treeconstroot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);// Construct the second treeconstroot2=newNode(1);root2.left=newNode(2);root2.right=newNode(3);root2.left.left=newNode(4);root2.left.right=newNode(5);// Check if the trees are identicalif(isIdentical(root1,root2))console.log("Both trees are identical");elseconsole.log("Both trees are not identical");}// Run the main functionmain();
Output
Both trees are identical
Time Complexity: O(N) , The time complexity of the isIdentical function is O(n), where n is the total number of nodes in the trees. This is because we visit each node exactly once and perform a constant amount of work at each node.
Auxiliary Space: O(H) , The space complexity of the isIdentical function is O(h), where h is the maximum height of the two trees. This is because we use two stacks to keep track of the nodes in the two trees This article is contributed by Ankur Lathiya .