Program to Determine if given Two Trees are Identical or not
Last Updated :
23 Jul, 2025
Given two binary trees, the task is to find if both of them are identical or not. Two trees are identical when they have the same data and the arrangement of data is also the same.
Examples:
Input:
Output: Yes
Explanation: Trees are identical.
Input:
Output: No
Explanation: Trees are not identical.
[Expected Approach - 1] Using DFS - O(n) Time and O(n) Space
The idea is to compare the root nodes' 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.
Follow the given steps to solve the problem:
- If both trees are empty then return 1 (Base case)
- Else, If both trees are non-empty
- Check data of the root nodes (r1->data == r2->data)
- Check left subtrees recursively
- Check right subtrees recursively
- If the above three statements are true then return 1
- Else return 0 (one is empty and the other is not)
Below is the implementation of the above approach:
C++
// C++ program to see if two trees are identical
// using DFS
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// Function to check if two trees are identical
bool isIdentical(Node* r1, Node* r2) {
// If both trees are empty, they are identical
if (r1 == nullptr && r2 == nullptr)
return true;
// If only one tree is empty, they are not identical
if (r1 == nullptr || r2 == nullptr)
return false;
// Check if the root data is the same and
// recursively check for the left and right subtrees
return (r1->data == r2->data) &&
isIdentical(r1->left, r2->left) &&
isIdentical(r1->right, r2->right);
}
int main() {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node* r1 = new Node(1);
r1->left = new Node(2);
r1->right = new Node(3);
r1->left->left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node* r2 = new Node(1);
r2->left = new Node(2);
r2->right = new Node(3);
r2->left->left = new Node(4);
if (isIdentical(r1, r2))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
C
// C program to see if two trees are identical
// using DFS
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
// Function to check if two trees are identical
bool isIdentical(struct Node* r1, struct Node* r2) {
// If both trees are empty, they are identical
if (r1 == NULL && r2 == NULL)
return true;
// If only one tree is empty, they are not identical
if (r1 == NULL || r2 == NULL)
return false;
// Check if the root data is the same and
// recursively check for the left and right subtrees
return (r1->data == r2->data) &&
isIdentical(r1->left, r2->left) &&
isIdentical(r1->right, r2->right);
}
struct Node* createNode(int val) {
struct Node *newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->left = newNode->right = NULL;
return newNode;
}
int main() {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
struct Node *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
// /
// 4
struct Node *r2 = createNode(1);
r2->left = createNode(2);
r2->right = createNode(3);
r2->left->left = createNode(4);
if (isIdentical(r1, r2))
printf("Yes\n");
else
printf("No\n");
return 0;
}
Java
// Java program to see if two trees are identical
// using DFS
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if two trees are identical
static boolean isIdentical(Node r1, Node r2) {
// If both trees are empty, they are identical
if (r1 == null && r2 == null)
return true;
// If only one tree is empty, they are not identical
if (r1 == null || r2 == null)
return false;
// Check if the root data is the same and
// recursively check for the left and right subtrees
return (r1.data == r2.data) &&
isIdentical(r1.left, r2.left) &&
isIdentical(r1.right, r2.right);
}
public static void main(String[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python
# Python program to see if two trees are identical
# using DFS
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if two trees are identical
def isIdentical(r1, r2):
# If both trees are empty, they are identical
if r1 is None and r2 is None:
return True
# If only one tree is empty, they are not identical
if r1 is None or r2 is None:
return False
# Check if the root data is the same and
# recursively check for the left and right subtrees
return (r1.data == r2.data and
isIdentical(r1.left, r2.left) and
isIdentical(r1.right, r2.right))
if __name__ == "__main__":
# Representation of input binary tree 1
# 1
# / \
# 2 3
# /
# 4
r1 = Node(1)
r1.left = Node(2)
r1.right = Node(3)
r1.left.left = Node(4)
# Representation of input binary tree 2
# 1
# / \
# 2 3
# /
# 4
r2 = Node(1)
r2.left = Node(2)
r2.right = Node(3)
r2.left.left = Node(4)
if isIdentical(r1, r2):
print("Yes")
else:
print("No")
C#
// C# program to see if two trees are identical
// using DFS
using System;
class Node {
public int Data;
public Node left, right;
public Node(int val) {
Data = val;
left = right = null;
}
}
class GfG {
// Function to check if two trees are identical
static bool isIdentical(Node r1, Node r2) {
// If both trees are empty, they are identical
if (r1 == null && r2 == null)
return true;
// If only one tree is empty, they are not identical
if (r1 == null || r2 == null)
return false;
// Check if the root data is the same and
// recursively check for the left and right subtrees
return (r1.Data == r2.Data) &&
isIdentical(r1.left, r2.left) &&
isIdentical(r1.right, r2.right);
}
static void Main(string[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
JavaScript
// Javascript program to see if two trees are identical
// using DFS
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to check if two trees are identical
function isIdentical(r1, r2) {
// If both trees are empty, they are identical
if (r1 === null && r2 === null)
return true;
// If only one tree is empty, they are not identical
if (r1 === null || r2 === null)
return false;
// Check if the root data is the same and
// recursively check for the left and right subtrees
return (r1.data === r2.data &&
isIdentical(r1.left, r2.left) &&
isIdentical(r1.right, r2.right));
}
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
let r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}
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.
[Expected Approach - 2] Using Level Order Traversal (BFS) - O(n) Time and O(n) Space
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. This approach ensures that the trees are identical in both structure and node values if all nodes match and the queues are empty at the end.
Follow the below steps to implement the above idea:
- Enqueue the root nodes of both trees into a queue.
- While the queue is not empty, dequeue the front nodes of both trees and compare their values.
- If the values are not equal, return false.
- If the values are equal, enqueue the left and right child nodes of both trees, if they exist, into the queue.
- Repeat steps 2-4 until either the queue becomes empty or we find two nodes with unequal values.
- If the queue becomes empty and we have not found any nodes with unequal values, return true indicating that the trees are identical.
Below is the implementation of the above approach:
C++
// C++ program to see if two trees are identical
// using Level Order Traversal(BFS)
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// Function to check if two trees are identical
// using level order traversal
bool isIdentical(Node* r1, Node* r2) {
if (r1 == nullptr && r2 == nullptr)
return true;
if (r1 == nullptr || r2 == nullptr)
return false;
// Use two queues for level order traversal
queue<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 identical
if (node1->data != node2->data)
return false;
// Check the left children
if (node1->left && node2->left) {
q1.push(node1->left);
q2.push(node2->left);
} else if (node1->left || node2->left) {
return false;
}
// Check the right children
if (node1->right && node2->right) {
q1.push(node1->right);
q2.push(node2->right);
} else if (node1->right || node2->right) {
return false;
}
}
// If both queues are empty, the trees are identical
return q1.empty() && q2.empty();
}
int main() {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node* r1 = new Node(1);
r1->left = new Node(2);
r1->right = new Node(3);
r1->left->left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node* r2 = new Node(1);
r2->left = new Node(2);
r2->right = new Node(3);
r2->left->left = new Node(4);
if (isIdentical(r1, r2))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
Java
// Java program to see if two trees are identical
// using Level Order Traversal(BFS)
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if two trees are identical
// using level-order traversal
static boolean isIdentical(Node r1, Node r2) {
// If both trees are empty, they are identical
if (r1 == null && r2 == null)
return true;
// If one tree is empty and the other is not
if (r1 == null || r2 == null)
return false;
// Queues to store nodes for level-order traversal
Queue<Node> q1 = new LinkedList<>();
Queue<Node> q2 = new LinkedList<>();
q1.add(r1);
q2.add(r2);
// Perform level-order traversal for both trees
while (!q1.isEmpty() && !q2.isEmpty()) {
Node n1 = q1.poll();
Node n2 = q2.poll();
// Check if the current nodes are not equal
if (n1.data != n2.data)
return false;
// Check left children
if (n1.left != null && n2.left != null) {
q1.add(n1.left);
q2.add(n2.left);
}
else if (n1.left != null || n2.left != null) {
return false;
}
// Check right children
if (n1.right != null && n2.right != null) {
q1.add(n1.right);
q2.add(n2.right);
}
else if (n1.right != null || n2.right != null) {
return false;
}
}
// Both queues should be empty if trees are identical
return q1.isEmpty() && q2.isEmpty();
}
public static void main(String[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python
# Python program to see if two trees are identical
# using Level Order Traversal(BFS)
from collections import deque
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if two trees are identical
# using level-order traversal
def isIdentical(r1, r2):
# If both trees are empty, they are identical
if r1 is None and r2 is None:
return True
# If one tree is empty and the other is not
if r1 is None or r2 is None:
return False
# Queues for level-order traversal
q1 = deque([r1])
q2 = deque([r2])
# Perform level-order traversal for both trees
while q1 and q2:
n1 = q1.popleft()
n2 = q2.popleft()
# Check if the current nodes are not equal
if n1.data != n2.data:
return False
# Check left children
if n1.left and n2.left:
q1.append(n1.left)
q2.append(n2.left)
elif n1.left or n2.left:
return False
# Check right children
if n1.right and n2.right:
q1.append(n1.right)
q2.append(n2.right)
elif n1.right or n2.right:
return False
# Both queues should be empty if trees are identical
return not q1 and not q2
if __name__ == "__main__":
# Representation of input binary tree 1
# 1
# / \
# 2 3
# /
# 4
r1 = Node(1)
r1.left = Node(2)
r1.right = Node(3)
r1.left.left = Node(4)
# Representation of input binary tree 2
# 1
# / \
# 2 3
# /
# 4
r2 = Node(1)
r2.left = Node(2)
r2.right = Node(3)
r2.left.left = Node(4)
if isIdentical(r1, r2):
print("Yes")
else:
print("No")
C#
// C# program to see if two trees are identical
// using Level Order Traversal(BFS)
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if two trees are identical
// using level-order traversal
static bool IsIdentical(Node r1, Node r2) {
// If both trees are empty, they are identical
if (r1 == null && r2 == null)
return true;
// If one tree is empty and the other is not
if (r1 == null || r2 == null)
return false;
// Queues for level-order traversal
Queue<Node> q1 = new Queue<Node>();
Queue<Node> q2 = new Queue<Node>();
q1.Enqueue(r1);
q2.Enqueue(r2);
// Perform level-order traversal for both trees
while (q1.Count > 0 && q2.Count > 0) {
Node n1 = q1.Dequeue();
Node n2 = q2.Dequeue();
// Check if the current nodes' data are not equal
if (n1.data != n2.data)
return false;
// Check left children
if (n1.left != null && n2.left != null) {
q1.Enqueue(n1.left);
q2.Enqueue(n2.left);
}
else if (n1.left != null || n2.left != null) {
return false;
}
// Check right children
if (n1.right != null && n2.right != null) {
q1.Enqueue(n1.right);
q2.Enqueue(n2.right);
}
else if (n1.right != null || n2.right != null) {
return false;
}
}
// Both queues should be empty if trees are
// identical
return q1.Count == 0 && q2.Count == 0;
}
static void Main(string[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (IsIdentical(r1, r2))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
JavaScript
// Javascript program to see if two trees are identical
// using Level Order Traversal(BFS)
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to check if two trees are identical
// using level-order traversal
function isIdentical(r1, r2) {
// If both trees are empty, they are identical
if (r1 === null && r2 === null)
return true;
// If one tree is empty and the other is not
if (r1 === null || r2 === null)
return false;
// Queues for level-order traversal
let queue1 = [r1];
let queue2 = [r2];
// Perform level-order traversal for both trees
while (queue1.length > 0 && queue2.length > 0) {
let node1 = queue1.shift();
let node2 = queue2.shift();
// Check if the current nodes' data are not equal
if (node1.data !== node2.data)
return false;
// Check left children
if (node1.left && node2.left) {
queue1.push(node1.left);
queue2.push(node2.left);
}
else if (node1.left || node2.left) {
return false;
}
// Check right children
if (node1.right && node2.right) {
queue1.push(node1.right);
queue2.push(node2.right);
}
else if (node1.right || node2.right) {
return false;
}
}
// Both queues should be empty if trees are identical
return queue1.length === 0 && queue2.length === 0;
}
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
let r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}
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 - 3] Using Morris Traversal - O(n) Time and O(1) Space
The idea is to use Morris traversal for comparing two trees, traverse both trees simultaneously by starting at their roots. For each node, if the left subtree exists, find the rightmost node in the left subtree (the predecessor) and create a temporary link back to the current node. Then, move to the left subtree. If no left subtree exists, compare the current nodes of both trees and move to the right subtree. At each step, compare the values of the corresponding nodes and ensure the structure matches. If at any point the values or structure differ, the trees are not identical. The process continues until both trees are fully traversed, and any temporary links created are removed. If no mismatches are found, the trees are identical.
Follow the steps to implement the above idea:
- Check if both trees are empty. If they are, return true. If only one of them is empty, return false.
- Perform the Morris traversal for in-order traversal of both trees simultaneously. At each step, compare the nodes visited in both trees.
- If at any step, the nodes visited in both trees are not equal, return false.
- If we reach the end of both trees simultaneously (i.e., both nodes are NULL), return true.
Below is the implementation of the above approach:
C++
// C++ program to see if two trees are identical
// using Morris Traversal
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// Function to check if two trees are
// identical using Morris traversal
bool isIdentical(Node* r1, Node* r2) {
// Check if both trees are empty
if (r1 == nullptr && r2 == nullptr)
return true;
// Check if one tree is empty and the other is not
if (r1 == nullptr || r2 == nullptr)
return false;
// Morris traversal to compare both trees
while (r1 != nullptr && r2 != nullptr) {
// Compare the data of both current nodes
if (r1->data != r2->data)
return false;
// Morris traversal for the first tree (r1)
if (r1->left == nullptr) {
// Move to the right child if no left child
r1 = r1->right;
} else {
// Find the inorder predecessor of r1
Node* pre = r1->left;
while (pre->right != nullptr
&& pre->right != r1) {
pre = pre->right;
}
// Set the temporary link to r1
if (pre->right == nullptr) {
pre->right = r1;
r1 = r1->left;
}
// Remove the temporary link and move to right
else {
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 child
r2 = r2->right;
} else {
// Find the inorder predecessor of r2
Node* pre = r2->left;
while (pre->right != nullptr
&& pre->right != r2) {
pre = pre->right;
}
// Set the temporary link to r2
if (pre->right == nullptr) {
pre->right = r2;
r2 = r2->left;
}
// Remove the temporary link and move to right
else {
pre->right = nullptr;
r2 = r2->right;
}
}
}
// Both trees are identical if both are null at end
return (r1 == nullptr && r2 == nullptr);
}
int main() {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node* r1 = new Node(1);
r1->left = new Node(2);
r1->right = new Node(3);
r1->left->left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node* r2 = new Node(1);
r2->left = new Node(2);
r2->right = new Node(3);
r2->left->left = new Node(4);
if (isIdentical(r1, r2))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
C
// C program to see if two trees are identical
// using Morris Traversal
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
// Function to check if two trees are identical
// using Morris traversal
int isIdentical(struct Node* r1, struct Node* r2) {
// Check if both trees are empty
if (r1 == NULL && r2 == NULL)
return 1;
// Check if one tree is empty and the other is not
if (r1 == NULL || r2 == NULL)
return 0;
// Morris traversal to compare both trees
while (r1 != NULL && r2 != NULL) {
// Compare the data of both current nodes
if (r1->data != r2->data)
return 0;
// Morris traversal for the first tree (r1)
if (r1->left == NULL) {
// Move to the right child if no left child
r1 = r1->right;
} else {
// Find the inorder predecessor of r1
struct Node* pre = r1->left;
while (pre->right != NULL && pre->right != r1) {
pre = pre->right;
}
// Set the temporary link to r1
if (pre->right == NULL) {
pre->right = r1;
r1 = r1->left;
}
// Remove the temporary link and move to right
else {
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 child
r2 = r2->right;
} else {
// Find the inorder predecessor of r2
struct Node* pre = r2->left;
while (pre->right != NULL && pre->right != r2) {
pre = pre->right;
}
// Set the temporary link to r2
if (pre->right == NULL) {
pre->right = r2;
r2 = r2->left;
}
// Remove the temporary link and move to right
else {
pre->right = NULL;
r2 = r2->right;
}
}
}
// Both trees are identical if both are
// null at the end
return (r1 == NULL && r2 == NULL);
}
struct Node* createNode(int val) {
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = val;
node->left = node->right = NULL;
return node;
}
int main() {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
struct Node* 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
// /
// 4
struct Node* r2 = createNode(1);
r2->left = createNode(2);
r2->right = createNode(3);
r2->left->left = createNode(4);
if (isIdentical(r1, r2))
printf("Yes\n");
else
printf("No\n");
return 0;
}
Java
// Java program to see if two trees are identical
// using Morris Traversal
import java.util.*;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if two trees are identical
// using Morris traversal
static boolean isIdentical(Node r1, Node r2) {
// Check if both trees are empty
if (r1 == null && r2 == null)
return true;
// Check if one tree is empty and the other is not
if (r1 == null || r2 == null)
return false;
// Morris traversal to compare both trees
while (r1 != null && r2 != null) {
// Compare the data of both current nodes
if (r1.data != r2.data)
return false;
// Morris traversal for the first tree (r1)
if (r1.left == null) {
// Move to the right child if no left child
r1 = r1.right;
}
else {
// Find the inorder predecessor of r1
Node pre = r1.left;
while (pre.right != null && pre.right != r1) {
pre = pre.right;
}
// Set the temporary link to r1
if (pre.right == null) {
pre.right = r1;
r1 = r1.left;
}
// Remove the temporary link and move to right
else {
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 child
r2 = r2.right;
}
else {
// Find the inorder predecessor of r2
Node pre = r2.left;
while (pre.right != null && pre.right != r2) {
pre = pre.right;
}
// Set the temporary link to r2
if (pre.right == null) {
pre.right = r2;
r2 = r2.left;
}
// Remove the temporary link and move to right
else {
pre.right = null;
r2 = r2.right;
}
}
}
// Both trees are identical if both are
// null at the end
return (r1 == null && r2 == null);
}
public static void main(String[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python
# Python program to see if two trees are identical
# using Morris Traversal
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if two trees are identical
# using Morris traversal
def isIdentical(r1, r2):
# Check if both trees are empty
if r1 is None and r2 is None:
return True
# Check if one tree is empty and the other is not
if r1 is None or r2 is None:
return False
# Morris traversal to compare both trees
while r1 is not None and r2 is not None:
# Compare the data of both current nodes
if r1.data != r2.data:
return False
# Morris traversal for the first tree (r1)
if r1.left is None:
# Move to the right child if no left child
r1 = r1.right
else:
# Find the inorder predecessor of r1
pre = r1.left
while pre.right is not None and pre.right != r1:
pre = pre.right
# Set the temporary link to r1
if pre.right is None:
pre.right = r1
r1 = r1.left
# Remove the temporary link and move to right
else:
pre.right = None
r1 = r1.right
# Morris traversal for the second tree (r2)
if r2.left is None:
# Move to the right child if no left child
r2 = r2.right
else:
# Find the inorder predecessor of r2
pre = r2.left
while pre.right is not None and pre.right != r2:
pre = pre.right
# Set the temporary link to r2
if pre.right is None:
pre.right = r2
r2 = r2.left
# Remove the temporary link and move to right
else:
pre.right = None
r2 = r2.right
# Both trees are identical if both are null at end
return r1 is None and r2 is None
if __name__ == '__main__':
# Representation of input binary tree 1
# 1
# / \
# 2 3
# /
# 4
r1 = Node(1)
r1.left = Node(2)
r1.right = Node(3)
r1.left.left = Node(4)
# Representation of input binary tree 2
# 1
# / \
# 2 3
# /
# 4
r2 = Node(1)
r2.left = Node(2)
r2.right = Node(3)
r2.left.left = Node(4)
if isIdentical(r1, r2):
print("Yes")
else:
print("No")
C#
// C# program to see if two trees are identical
// using Morris Traversal
using System;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if two trees are identical
// using Morris traversal
static bool IsIdentical(Node r1, Node r2) {
// Check if both trees are empty
if (r1 == null && r2 == null)
return true;
// Check if one tree is empty and the other is not
if (r1 == null || r2 == null)
return false;
// Morris traversal to compare both trees
while (r1 != null && r2 != null) {
// Compare the data of both current nodes
if (r1.data != r2.data)
return false;
// Morris traversal for the first tree (r1)
if (r1.left == null) {
// Move to the right child if no left child
r1 = r1.right;
}
else {
// Find the inorder predecessor of r1
Node pre = r1.left;
while (pre.right != null && pre.right != r1) {
pre = pre.right;
}
// Set the temporary link to r1
if (pre.right == null) {
pre.right = r1;
r1 = r1.left;
}
// Remove the temporary link and move to right
else {
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 child
r2 = r2.right;
}
else {
// Find the inorder predecessor of r2
Node pre = r2.left;
while (pre.right != null && pre.right != r2) {
pre = pre.right;
}
// Set the temporary link to r2
if (pre.right == null) {
pre.right = r2;
r2 = r2.left;
}
// Remove the temporary link and move to right
else {
pre.right = null;
r2 = r2.right;
}
}
}
// Both trees are identical if both are
// null at end
return (r1 == null && r2 == null);
}
static void Main(string[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
Node r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
Node r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (IsIdentical(r1, r2))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
JavaScript
// Javascript program to see if two trees are identical
// using Morris Traversal
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to check if two trees are identical
// using Morris traversal
function isIdentical(r1, r2) {
// Check if both trees are empty
if (r1 === null && r2 === null) {
return true;
}
// Check if one tree is empty and the other is not
if (r1 === null || r2 === null) {
return false;
}
// Morris traversal to compare both trees
while (r1 !== null && r2 !== null) {
// Compare the data of both current nodes
if (r1.data !== r2.data) {
return false;
}
// Morris traversal for the first tree (r1)
if (r1.left === null) {
// Move to the right child if no left child
r1 = r1.right;
}
else {
// Find the inorder predecessor of r1
let pre = r1.left;
while (pre.right !== null && pre.right !== r1) {
pre = pre.right;
}
// Set the temporary link to r1
if (pre.right === null) {
pre.right = r1;
r1 = r1.left;
}
// Remove the temporary link and move to right
else {
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 child
r2 = r2.right;
}
else {
// Find the inorder predecessor of r2
let pre = r2.left;
while (pre.right !== null && pre.right !== r2) {
pre = pre.right;
}
// Set the temporary link to r2
if (pre.right === null) {
pre.right = r2;
r2 = r2.left;
}
// Remove the temporary link and move to right
else {
pre.right = null;
r2 = r2.right;
}
}
}
// Both trees are identical if both are null at end
return r1 === null && r2 === null;
}
// Representation of input binary tree 1
// 1
// / \
// 2 3
// /
// 4
let r1 = new Node(1);
r1.left = new Node(2);
r1.right = new Node(3);
r1.left.left = new Node(4);
// Representation of input binary tree 2
// 1
// / \
// 2 3
// /
// 4
let r2 = new Node(1);
r2.left = new Node(2);
r2.right = new Node(3);
r2.left.left = new Node(4);
if (isIdentical(r1, r2)) {
console.log("Yes");
}
else {
console.log("No");
}
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), Morris traversal modifies the tree temporarily by establishing "threads" to traverse nodes without using recursion or a stack.
Determine if Two Trees are Identical | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem