Given the roots r1 and r2 of two binary trees, determine whether they are identical. Two trees are considered identical if they have the same structure and the same node values.
Examples:
Input:
Output: true Explanation: Trees are identical, having same node structure and node values.
Input:
Output: false Explanation: Trees are not identical, both have different node structure.
The idea is to compare the root node's data and recursively verify that their left and right subtrees are identical. Both trees must have the same structure and data at each corresponding node.
C++
#include<iostream>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};boolisIdentical(Node*r1,Node*r2){// If both trees are empty, they are identicalif(r1==nullptr&&r2==nullptr)returntrue;// If only one tree is empty, they are not identicalif(r1==nullptr||r2==nullptr)returnfalse;// Check if the root data is the same and// recursively check for the left and right subtreesreturn(r1->data==r2->data)&&isIdentical(r1->left,r2->left)&&isIdentical(r1->right,r2->right);}intmain(){// Representation of input binary tree 1// 1// / \ // 2 3// /// 4Node*r1=newNode(1);r1->left=newNode(2);r1->right=newNode(3);r1->left->left=newNode(4);// Representation of input binary tree 2// 1// / \ // 2 3// /// 4Node*r2=newNode(1);r2->left=newNode(2);r2->right=newNode(3);r2->left->left=newNode(4);if(isIdentical(r1,r2))cout<<"true\n";elsecout<<"false\n";return0;}
C
#include<stdio.h>#include<stdbool.h>#include<stdlib.h>// Node structurestructNode{intdata;structNode*left,*right;};boolisIdentical(structNode*r1,structNode*r2){// If both trees are empty, they are identicalif(r1==NULL&&r2==NULL)returntrue;// If only one tree is empty, they are not identicalif(r1==NULL||r2==NULL)returnfalse;// Check if the root data is the same and// recursively check for the left and right subtreesreturn(r1->data==r2->data)&&isIdentical(r1->left,r2->left)&&isIdentical(r1->right,r2->right);}structNode*createNode(intval){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=val;newNode->left=newNode->right=NULL;returnnewNode;}intmain(){// Representation of input binary tree 1// 1// / \ // 2 3// /// 4structNode*r1=createNode(1);r1->left=createNode(2);r1->right=createNode(3);r1->left->left=createNode(4);// Representation of input binary tree 2// 1// / \ // 2 3// /// 4structNode*r2=createNode(1);r2->left=createNode(2);r2->right=createNode(3);r2->left->left=createNode(4);if(isIdentical(r1,r2))printf("true\n");elseprintf("false\n");return0;}
Java
// Node structureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGfG{staticbooleanisIdentical(Noder1,Noder2){// If both trees are empty, they are identicalif(r1==null&&r2==null)returntrue;// If only one tree is empty, they are not identicalif(r1==null||r2==null)returnfalse;// Check if the root data is the same and// recursively check for the left and right subtreesreturn(r1.data==r2.data)&&isIdentical(r1.left,r2.left)&&isIdentical(r1.right,r2.right);}publicstaticvoidmain(String[]args){// Representation of input binary tree 1// 1// / \// 2 3// /// 4Noder1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4Noder2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))System.out.println("true");elseSystem.out.println("false");}}
Python
# Node structureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefisIdentical(r1,r2):# If both trees are empty, they are identicalifr1isNoneandr2isNone:returnTrue# If only one tree is empty, they are not identicalifr1isNoneorr2isNone:returnFalse# Check if the root data is the same and# recursively check for the left and right subtreesreturn(r1.data==r2.dataandisIdentical(r1.left,r2.left)andisIdentical(r1.right,r2.right))if__name__=="__main__":# Representation of input binary tree 1# 1# / \# 2 3# /# 4r1=Node(1)r1.left=Node(2)r1.right=Node(3)r1.left.left=Node(4)# Representation of input binary tree 2# 1# / \# 2 3# /# 4r2=Node(1)r2.left=Node(2)r2.right=Node(3)r2.left.left=Node(4)ifisIdentical(r1,r2):print("true")else:print("false")
C#
usingSystem;// Node structureclassNode{publicintData;publicNodeleft,right;publicNode(intval){Data=val;left=right=null;}}classGfG{staticboolisIdentical(Noder1,Noder2){// If both trees are empty, they are identicalif(r1==null&&r2==null)returntrue;// If only one tree is empty, they are not identicalif(r1==null||r2==null)returnfalse;// Check if the root data is the same and// recursively check for the left and right subtreesreturn(r1.Data==r2.Data)&&isIdentical(r1.left,r2.left)&&isIdentical(r1.right,r2.right);}staticvoidMain(string[]args){// Representation of input binary tree 1// 1// / \// 2 3// /// 4Noder1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4Noder2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Node structureclassNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionisIdentical(r1,r2){// If both trees are empty, they are identicalif(r1===null&&r2===null)returntrue;// If only one tree is empty, they are not identicalif(r1===null||r2===null)returnfalse;// Check if the root data is the same and// recursively check for the left and right subtreesreturn(r1.data===r2.data&&isIdentical(r1.left,r2.left)&&isIdentical(r1.right,r2.right));}//Driver Code// Representation of input binary tree 1// 1// / \// 2 3// /// 4letr1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4letr2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2)){console.log("true");}else{console.log("false");}
Output
true
Time Complexity:O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once. Auxiliary Space: O(h), where h is the height of the trees, due to the recursive call stack.
[Approach - 2] Using Level Order Traversal (BFS)
The idea is to use level order traversal with two queues to compare the structure and data of two trees. By enqueuing nodes from both trees simultaneously, we can compare corresponding nodes at each level. If nodes at any level differ in data or structure, or if one tree has nodes where the other does not, the trees are not identical.
C++
#include<iostream>#include<queue>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};boolisIdentical(Node*r1,Node*r2){if(r1==nullptr&&r2==nullptr)returntrue;if(r1==nullptr||r2==nullptr)returnfalse;// Use two queues for level order traversalqueue<Node*>q1,q2;q1.push(r1);q2.push(r2);while(!q1.empty()&&!q2.empty()){Node*node1=q1.front();Node*node2=q2.front();q1.pop();q2.pop();// Check if the current nodes are identicalif(node1->data!=node2->data)returnfalse;// Check the left childrenif(node1->left&&node2->left){q1.push(node1->left);q2.push(node2->left);}elseif(node1->left||node2->left){returnfalse;}// Check the right childrenif(node1->right&&node2->right){q1.push(node1->right);q2.push(node2->right);}elseif(node1->right||node2->right){returnfalse;}}// If both queues are empty, the trees are identicalreturnq1.empty()&&q2.empty();}intmain(){// Representation of input binary tree 1// 1// / \ // 2 3// /// 4Node*r1=newNode(1);r1->left=newNode(2);r1->right=newNode(3);r1->left->left=newNode(4);// Representation of input binary tree 2// 1// / \ // 2 3// /// 4Node*r2=newNode(1);r2->left=newNode(2);r2->right=newNode(3);r2->left->left=newNode(4);if(isIdentical(r1,r2))cout<<"true\n";elsecout<<"false\n";return0;}
C
#include<stdio.h>#include<stdlib.h>#include<stdbool.h>// Node structurestructNode{intdata;structNode*left;structNode*right;}// Queue node for level order traversalstructQueueNode{Node*treeNode;structQueueNode*next;}// Queue structurestructQueue{QueueNode*front;QueueNode*rear;}// Create a new tree nodeNode*newNode(intval){Node*node=(Node*)malloc(sizeof(Node));node->data=val;node->left=node->right=NULL;returnnode;}// Queue functionsQueue*createQueue(){Queue*q=(Queue*)malloc(sizeof(Queue));q->front=q->rear=NULL;returnq;}boolisEmpty(Queue*q){returnq->front==NULL;}voidenqueue(Queue*q,Node*node){QueueNode*temp=(QueueNode*)malloc(sizeof(QueueNode));temp->treeNode=node;temp->next=NULL;if(q->rear==NULL){q->front=q->rear=temp;return;}q->rear->next=temp;q->rear=temp;}Node*dequeue(Queue*q){if(isEmpty(q))returnNULL;QueueNode*temp=q->front;Node*node=temp->treeNode;q->front=q->front->next;if(q->front==NULL)q->rear=NULL;free(temp);returnnode;}boolisIdentical(Node*r1,Node*r2){if(r1==NULL&&r2==NULL)returntrue;if(r1==NULL||r2==NULL)returnfalse;// Use two queues for level order traversalQueue*q1=createQueue();Queue*q2=createQueue();enqueue(q1,r1);enqueue(q2,r2);while(!isEmpty(q1)&&!isEmpty(q2)){Node*node1=dequeue(q1);Node*node2=dequeue(q2);// Check if the current nodes are identicalif(node1->data!=node2->data)returnfalse;// Check left childrenif(node1->left&&node2->left){enqueue(q1,node1->left);enqueue(q2,node2->left);}elseif(node1->left||node2->left){returnfalse;}// Check right childrenif(node1->right&&node2->right){enqueue(q1,node1->right);enqueue(q2,node2->right);}elseif(node1->right||node2->right){returnfalse;}}// If both queues are empty, the trees are identicalreturnisEmpty(q1)&&isEmpty(q2);}intmain(){// Representation of input binary tree 1// 1// / \ // 2 3// /// 4Node*r1=newNode(1);r1->left=newNode(2);r1->right=newNode(3);r1->left->left=newNode(4);// Representation of input binary tree 2// 1// / \ // 2 3// /// 4Node*r2=newNode(1);r2->left=newNode(2);r2->right=newNode(3);r2->left->left=newNode(4);if(isIdentical(r1,r2))printf("true\n");elseprintf("false\n");return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;// Node structureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassGFG{staticbooleanisIdentical(Noder1,Noder2){if(r1==null&&r2==null)returntrue;if(r1==null||r2==null)returnfalse;// Use two queues for level order traversalQueue<Node>q1=newLinkedList<>();Queue<Node>q2=newLinkedList<>();q1.add(r1);q2.add(r2);while(!q1.isEmpty()&&!q2.isEmpty()){Nodenode1=q1.poll();Nodenode2=q2.poll();// Check if the current nodes are identicalif(node1.data!=node2.data)returnfalse;// Check the left childrenif(node1.left!=null&&node2.left!=null){q1.add(node1.left);q2.add(node2.left);}elseif(node1.left!=null||node2.left!=null){returnfalse;}// Check the right childrenif(node1.right!=null&&node2.right!=null){q1.add(node1.right);q2.add(node2.right);}elseif(node1.right!=null||node2.right!=null){returnfalse;}}// If both queues are empty, the trees are identicalreturnq1.isEmpty()&&q2.isEmpty();}publicstaticvoidmain(String[]args){// Representation of input binary tree 1// 1// / \// 2 3// /// 4Noder1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4Noder2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))System.out.println("true");elseSystem.out.println("false");}}
Python
fromcollectionsimportdeque# Node structureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefisIdentical(r1,r2):ifr1isNoneandr2isNone:returnTrueifr1isNoneorr2isNone:returnFalse# Use two queues for level order traversalq1=deque()q2=deque()q1.append(r1)q2.append(r2)whileq1andq2:node1=q1.popleft()node2=q2.popleft()# Check if the current nodes are identicalifnode1.data!=node2.data:returnFalse# Check the left childrenifnode1.leftandnode2.left:q1.append(node1.left)q2.append(node2.left)elifnode1.leftornode2.left:returnFalse# Check the right childrenifnode1.rightandnode2.right:q1.append(node1.right)q2.append(node2.right)elifnode1.rightornode2.right:returnFalse# If both queues are empty, the trees are identicalreturnnotq1andnotq2if__name__=="__main__":# Representation of input binary tree 1# 1# / \# 2 3# /# 4r1=Node(1)r1.left=Node(2)r1.right=Node(3)r1.left.left=Node(4)# Representation of input binary tree 2# 1# / \# 2 3# /# 4r2=Node(1)r2.left=Node(2)r2.right=Node(3)r2.left.left=Node(4)ifisIdentical(r1,r2):print("true")else:print("false")
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}publicclassGFG{publicstaticboolisIdentical(Noder1,Noder2){if(r1==null&&r2==null)returntrue;if(r1==null||r2==null)returnfalse;// Use two queues for level order traversalQueue<Node>q1=newQueue<Node>();Queue<Node>q2=newQueue<Node>();q1.Enqueue(r1);q2.Enqueue(r2);while(q1.Count>0&&q2.Count>0){Nodenode1=q1.Dequeue();Nodenode2=q2.Dequeue();// Check if the current nodes are identicalif(node1.data!=node2.data)returnfalse;// Check the left childrenif(node1.left!=null&&node2.left!=null){q1.Enqueue(node1.left);q2.Enqueue(node2.left);}elseif(node1.left!=null||node2.left!=null){returnfalse;}// Check the right childrenif(node1.right!=null&&node2.right!=null){q1.Enqueue(node1.right);q2.Enqueue(node2.right);}elseif(node1.right!=null||node2.right!=null){returnfalse;}}// If both queues are empty, the trees are identicalreturnq1.Count==0&&q2.Count==0;}publicstaticvoidMain(){// Representation of input binary tree 1// 1// / \// 2 3// /// 4Noder1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4Noder2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Node structurefunctionNode(val){this.data=val;this.left=null;this.right=null;}// Simple Queue classclassQueue{constructor(){this.items=[];this.frontIndex=0;}enqueue(item){this.items.push(item);}dequeue(){if(this.frontIndex<this.items.length){returnthis.items[this.frontIndex++];}returnnull;}isEmpty(){returnthis.frontIndex>=this.items.length;}}functionisIdentical(r1,r2){if(r1===null&&r2===null)returntrue;if(r1===null||r2===null)returnfalse;// Use two queues for level order traversalletq1=newQueue();letq2=newQueue();q1.enqueue(r1);q2.enqueue(r2);while(!q1.isEmpty()&&!q2.isEmpty()){letnode1=q1.dequeue();letnode2=q2.dequeue();// Check if the current nodes are identicalif(node1.data!==node2.data)returnfalse;// Check the left childrenif(node1.left&&node2.left){q1.enqueue(node1.left);q2.enqueue(node2.left);}elseif(node1.left||node2.left){returnfalse;}// Check the right childrenif(node1.right&&node2.right){q1.enqueue(node1.right);q2.enqueue(node2.right);}elseif(node1.right||node2.right){returnfalse;}}// If both queues are empty, the trees are identicalreturnq1.isEmpty()&&q2.isEmpty();}// Driver code// Representation of input binary tree 1// 1// / \// 2 3// / // 4letr1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// / // 4letr2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))console.log("true");elseconsole.log("false");
Output
true
Time complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once. Auxiliary Space: O(w), where w is the maximum width of the trees at any level, due to the space required for the queues.
[Expected Approach] Using Morris Traversal
Traverse both trees simultaneously using Morris traversal, comparing node values and structure without recursion or stacks. Temporary links are used to navigate subtrees efficiently, and all links are removed after traversal.
Steps:
Start at the root of both trees.
If a node has a left child, go to its left subtree and find the rightmost node there; temporarily link it back to the current node.
Move to the left child; if no left child, compare the nodes of both trees.
After left subtree, follow the temporary link back, then go to the right child.
If any node mismatch or missing node is found, return false.
Remove all temporary links.
Continue until all nodes are visited; if all match, return true.
C++
#include<iostream>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};boolisIdentical(Node*r1,Node*r2){if(r1==nullptr&&r2==nullptr)returntrue;if(r1==nullptr||r2==nullptr)returnfalse;while(r1!=nullptr&&r2!=nullptr){if(r1->data!=r2->data)returnfalse;// Morris traversal for the first tree (r1)if(r1->left==nullptr){// Move to the right child if no left childr1=r1->right;}else{// Find the inorder predecessor of r1Node*pre=r1->left;while(pre->right!=nullptr&&pre->right!=r1){pre=pre->right;}// Set the temporary link to r1if(pre->right==nullptr){pre->right=r1;r1=r1->left;}// Remove the temporary link and move to rightelse{pre->right=nullptr;r1=r1->right;}}// Morris traversal for the second tree (r2)if(r2->left==nullptr){// Move to the right child if no left childr2=r2->right;}else{// Find the inorder predecessor of r2Node*pre=r2->left;while(pre->right!=nullptr&&pre->right!=r2){pre=pre->right;}// Set the temporary link to r2if(pre->right==nullptr){pre->right=r2;r2=r2->left;}// Remove the temporary link and move to rightelse{pre->right=nullptr;r2=r2->right;}}}return(r1==nullptr&&r2==nullptr);}intmain(){// Representation of input binary tree 1// 1// / \ // 2 3// /// 4Node*r1=newNode(1);r1->left=newNode(2);r1->right=newNode(3);r1->left->left=newNode(4);// Representation of input binary tree 2// 1// / \ // 2 3// /// 4Node*r2=newNode(1);r2->left=newNode(2);r2->right=newNode(3);r2->left->left=newNode(4);if(isIdentical(r1,r2))cout<<"true\n";elsecout<<"false\n";return0;}
C
#include<stdio.h>#include<stdlib.h>// Node structurestructNode{intdata;structNode*left;structNode*right;};// Function to create a new nodestructNode*newNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}intisIdentical(structNode*r1,structNode*r2){if(r1==NULL&&r2==NULL)return1;if(r1==NULL||r2==NULL)return0;while(r1!=NULL&&r2!=NULL){if(r1->data!=r2->data)return0;// Morris traversal for the first tree (r1)if(r1->left==NULL){// Move to the right child if no left childr1=r1->right;}else{// Find the inorder predecessor of r1structNode*pre=r1->left;while(pre->right!=NULL&&pre->right!=r1){pre=pre->right;}// Set the temporary link to r1if(pre->right==NULL){pre->right=r1;r1=r1->left;}// Remove the temporary link and move to rightelse{pre->right=NULL;r1=r1->right;}}// Morris traversal for the second tree (r2)if(r2->left==NULL){// Move to the right child if no left childr2=r2->right;}else{// Find the inorder predecessor of r2structNode*pre=r2->left;while(pre->right!=NULL&&pre->right!=r2){pre=pre->right;}// Set the temporary link to r2if(pre->right==NULL){pre->right=r2;r2=r2->left;}// Remove the temporary link and move to rightelse{pre->right=NULL;r2=r2->right;}}}return(r1==NULL&&r2==NULL);}intmain(){// Representation of input binary tree 1// 1// / \ // 2 3// /// 4structNode*r1=newNode(1);r1->left=newNode(2);r1->right=newNode(3);r1->left->left=newNode(4);// Representation of input binary tree 2// 1// / \ // 2 3// /// 4structNode*r2=newNode(1);r2->left=newNode(2);r2->right=newNode(3);r2->left->left=newNode(4);if(isIdentical(r1,r2))printf("true\n");elseprintf("false\n");return0;}
Java
//Node StructureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGFG{staticbooleanisIdentical(Noder1,Noder2){if(r1==null&&r2==null)returntrue;if(r1==null||r2==null)returnfalse;while(r1!=null&&r2!=null){if(r1.data!=r2.data)returnfalse;// Morris traversal for the first tree (r1)if(r1.left==null){// Move to the right child if no left childr1=r1.right;}else{// Find the inorder predecessor of r1Nodepre=r1.left;while(pre.right!=null&&pre.right!=r1){pre=pre.right;}// Set the temporary link to r1if(pre.right==null){pre.right=r1;r1=r1.left;}// Remove the temporary link and move to rightelse{pre.right=null;r1=r1.right;}}// Morris traversal for the second tree (r2)if(r2.left==null){// Move to the right child if no left childr2=r2.right;}else{// Find the inorder predecessor of r2Nodepre=r2.left;while(pre.right!=null&&pre.right!=r2){pre=pre.right;}// Set the temporary link to r2if(pre.right==null){pre.right=r2;r2=r2.left;}// Remove the temporary link and move to rightelse{pre.right=null;r2=r2.right;}}}return(r1==null&&r2==null);}publicstaticvoidmain(String[]args){// Representation of input binary tree 1// 1// / \// 2 3// /// 4Noder1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4Noder2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))System.out.println("true");elseSystem.out.println("false");}}
Python
#Node StructureclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefisIdentical(r1,r2):ifr1isNoneandr2isNone:returnTrueifr1isNoneorr2isNone:returnFalsewhiler1isnotNoneandr2isnotNone:ifr1.data!=r2.data:returnFalse# Morris traversal for the first tree (r1)ifr1.leftisNone:# Move to the right child if no left childr1=r1.rightelse:# Find the inorder predecessor of r1pre=r1.leftwhilepre.rightisnotNoneandpre.right!=r1:pre=pre.right# Set the temporary link to r1ifpre.rightisNone:pre.right=r1r1=r1.left# Remove the temporary link and move to rightelse:pre.right=Noner1=r1.right# Morris traversal for the second tree (r2)ifr2.leftisNone:# Move to the right child if no left childr2=r2.rightelse:# Find the inorder predecessor of r2pre=r2.leftwhilepre.rightisnotNoneandpre.right!=r2:pre=pre.right# Set the temporary link to r2ifpre.rightisNone:pre.right=r2r2=r2.left# Remove the temporary link and move to rightelse:pre.right=Noner2=r2.rightreturnr1isNoneandr2isNoneif__name__=="__main__":# Representation of input binary tree 1# 1# / \# 2 3# /# 4r1=Node(1)r1.left=Node(2)r1.right=Node(3)r1.left.left=Node(4)# Representation of input binary tree 2# 1# / \# 2 3# /# 4r2=Node(1)r2.left=Node(2)r2.right=Node(3)r2.left.left=Node(4)ifisIdentical(r1,r2):print("true")else:print("false")
C#
usingSystem;//Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intv){data=v;left=right=null;}}classGFG{publicstaticboolisIdentical(Noder1,Noder2){if(r1==null&&r2==null)returntrue;if(r1==null||r2==null)returnfalse;while(r1!=null&&r2!=null){if(r1.data!=r2.data)returnfalse;// Morris traversal for the first tree (r1)if(r1.left==null){// Move to the right child if no left childr1=r1.right;}else{// Find the inorder predecessor of r1Nodepre=r1.left;while(pre.right!=null&&pre.right!=r1){pre=pre.right;}// Set the temporary link to r1if(pre.right==null){pre.right=r1;r1=r1.left;}// Remove the temporary link and move to rightelse{pre.right=null;r1=r1.right;}}// Morris traversal for the second tree (r2)if(r2.left==null){// Move to the right child if no left childr2=r2.right;}else{// Find the inorder predecessor of r2Nodepre=r2.left;while(pre.right!=null&&pre.right!=r2){pre=pre.right;}// Set the temporary link to r2if(pre.right==null){pre.right=r2;r2=r2.left;}// Remove the temporary link and move to rightelse{pre.right=null;r2=r2.right;}}}returnr1==null&&r2==null;}staticvoidMain(){// Representation of input binary tree 1// 1// / \// 2 3// /// 4Noder1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4Noder2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
// Node structureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}functionisIdentical(r1,r2){if(r1===null&&r2===null)returntrue;if(r1===null||r2===null)returnfalse;while(r1!==null&&r2!==null){if(r1.data!==r2.data)returnfalse;// Morris traversal for the first tree (r1)if(r1.left===null){// Move to the right child if no left childr1=r1.right;}else{// Find the inorder predecessor of r1letpre=r1.left;while(pre.right!==null&&pre.right!==r1){pre=pre.right;}// Set the temporary link to r1if(pre.right===null){pre.right=r1;r1=r1.left;}// Remove the temporary link and move to rightelse{pre.right=null;r1=r1.right;}}// Morris traversal for the second tree (r2)if(r2.left===null){// Move to the right child if no left childr2=r2.right;}else{// Find the inorder predecessor of r2letpre=r2.left;while(pre.right!==null&&pre.right!==r2){pre=pre.right;}// Set the temporary link to r2if(pre.right===null){pre.right=r2;r2=r2.left;}// Remove the temporary link and move to rightelse{pre.right=null;r2=r2.right;}}}return(r1===null&&r2===null);}// Driver code// Representation of input binary tree 1// 1// / \// 2 3// /// 4letr1=newNode(1);r1.left=newNode(2);r1.right=newNode(3);r1.left.left=newNode(4);// Representation of input binary tree 2// 1// / \// 2 3// /// 4letr2=newNode(1);r2.left=newNode(2);r2.right=newNode(3);r2.left.left=newNode(4);if(isIdentical(r1,r2))console.log("true");elseconsole.log("false");
Output
true
Time Complexity: O(n), where n is the number of nodes in the larger of the two trees, as each node is visited once. Auxiliary Space: O(1), modifying tree temporarily by establishing "threads" to traverse nodes without using recursion or a stack.