Iterative Approach to check if two Binary Trees are Isomorphic or not
Last Updated :
12 Jul, 2025
Given two Binary Trees, the task is to check whether they are isomorphic or not. Two trees are called isomorphic if one of them can be obtained from the other by a series of flips, i.e. by swapping left and right children of several nodes. Any number of nodes at any level can have their children swapped.
Note:
- If two trees are the same (same structure and node values), they are isomorphic.
- Two empty trees are isomorphic.
- If the root node values of both trees differ, they are not isomorphic.
Examples:
Input:

Output: True
Explanation: The above two trees are isomorphic with following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8.
Approach:
The idea is to traverse both trees iteratively using level-order traversal with a queue data structure. At each level, we will check two conditions:
- The values of the nodes must be the same.
- The number of nodes at each level must match.
We will traverse the first tree and record the nodes in a hashmap where each key represents the node value and its associated value indicates the count of that node at the current level. For the second tree, we will use a queue to traverse the nodes at the same level. At each step, we will compare the current node's value from the second tree with the keys in the map. If the key is found, we will decrement its value to keep track of how many nodes with the same value exist at that level. If the value becomes zero, we will remove it as a key from the map.
After processing all nodes at the level, we will check the map:
- If a key is not found, it indicates that the first tree does not contain a corresponding node from the second tree.
- If a key's value is negative, it means the second tree has more nodes with that value than the first tree.
- Lastly, if the map is not empty after processing a level, it indicates that the first tree has nodes that do not match any node in the second tree.
Below is the implementation of the above approach:
C++
// C++ code to check if two trees are
// isomorphic using Level Order Traversal
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Helper function to check if the second
// tree is isomorphic
bool CheckTree(Node *root2, map<pair<int, int>, bool> &visited) {
// If root of the second tree is not visited
if (visited[{root2->data, -1}] == false) {
return false;
}
queue<Node *> q;
q.push(root2);
// Traverse the second tree
while (!q.empty()) {
Node *curr = q.front();
q.pop();
if (curr->left) {
// If the left child has not been visited
if (visited[{curr->left->data, curr->data}] == false) {
return false;
}
q.push(curr->left);
}
if (curr->right) {
// If the right child has not been visited
if (visited[{curr->right->data, curr->data}] == false) {
return false;
}
q.push(curr->right);
}
}
return true;
}
// Main function to check if two trees are isomorphic
bool isIsomorphic(Node *root1, Node *root2) {
map<pair<int, int>, bool> visited;
// Mark the root of the first tree as visited
visited[{root1->data, -1}] = true;
queue<Node *> q;
q.push(root1);
// Traverse the first tree and mark nodes as visited
while (!q.empty()) {
Node *curr = q.front();
q.pop();
if (curr->left) {
visited[{curr->left->data, curr->data}] = true;
q.push(curr->left);
}
if (curr->right) {
visited[{curr->right->data, curr->data}] = true;
q.push(curr->right);
}
}
// Use the helper function to check the second tree
return CheckTree(root2, visited);
}
int main() {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// / \
// 4 5
// / \
// 7 8
Node *root1 = new Node(1);
root1->left = new Node(2);
root1->right = new Node(3);
root1->left->left = new Node(4);
root1->left->right = new Node(5);
root1->left->right->left = new Node(7);
root1->left->right->right = new Node(8);
// Representation of input binary tree 2
// 1
// / \
// 3 2
// / / \
// 6 4 5
// / \
// 8 7
Node *root2 = new Node(1);
root2->left = new Node(3);
root2->right = new Node(2);
root2->left->left = new Node(6);
root2->right->left = new Node(4);
root2->right->right = new Node(5);
root2->right->right->left = new Node(8);
root2->right->right->right = new Node(7);
if (isIsomorphic(root1, root2)) {
cout << "Yes\n";
}
else {
cout << "No\n";
}
return 0;
}
Java
// Java code to check if two trees are
// isomorphic using Level Order Traversal
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class Pair {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Pair pair = (Pair)obj;
return first == pair.first && second == pair.second;
}
@Override public int hashCode() {
return Objects.hash(first, second);
}
}
class GfG {
static boolean checkTree(Node root2,
Map<Pair, Boolean> visited) {
// If root of the second tree is not visited
if (!visited.containsKey(
new Pair(root2.data, -1))) {
return false;
}
Queue<Node> q = new LinkedList<>();
q.add(root2);
// Traverse the second tree
while (!q.isEmpty()) {
Node curr = q.poll();
if (curr.left != null) {
// If the left child has not been visited
if (!visited.containsKey(new Pair(
curr.left.data, curr.data))) {
return false;
}
q.add(curr.left);
}
if (curr.right != null) {
// If the right child has not been visited
if (!visited.containsKey(new Pair(
curr.right.data, curr.data))) {
return false;
}
q.add(curr.right);
}
}
return true;
}
// Main function to check if two trees are isomorphic
static boolean isIsomorphic(Node root1, Node root2) {
Map<Pair, Boolean> visited = new HashMap<>();
// Mark the root of the first tree as visited
visited.put(new Pair(root1.data, -1), true);
Queue<Node> q = new LinkedList<>();
q.add(root1);
// Traverse the first tree and mark nodes as visited
while (!q.isEmpty()) {
Node curr = q.poll();
if (curr.left != null) {
visited.put(
new Pair(curr.left.data, curr.data),
true);
q.add(curr.left);
}
if (curr.right != null) {
visited.put(
new Pair(curr.right.data, curr.data),
true);
q.add(curr.right);
}
}
// Use the helper function to check the second tree
return checkTree(root2, visited);
}
public static void main(String[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// / \
// 4 5
// / \
// 7 8
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.left.right.left = new Node(7);
root1.left.right.right = new Node(8);
// Representation of input binary tree 2
// 1
// / \
// 3 2
// / / \
// 6 4 5
// / \
// 8 7
Node root2 = new Node(1);
root2.left = new Node(3);
root2.right = new Node(2);
root2.left.left = new Node(6);
root2.right.left = new Node(4);
root2.right.right = new Node(5);
root2.right.right.left = new Node(8);
root2.right.right.right = new Node(7);
if (isIsomorphic(root1, root2)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
Python
# Python code to check if two trees are
# isomorphic using Level Order Traversal
from collections import deque
# Define the Node class for the tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Helper function to check if the second tree is isomorphic
def check_tree(root2, visited):
if (root2.data, -1) not in visited:
return False
queue = [root2]
while queue:
curr = queue.pop(0)
if curr.left:
if (curr.left.data, curr.data) not in visited:
return False
queue.append(curr.left)
if curr.right:
if (curr.right.data, curr.data) not in visited:
return False
queue.append(curr.right)
return True
# Main function to check if two trees are isomorphic
def isIsomorphic(root1, root2):
visited = set()
# Mark the root of the first tree as visited
visited.add((root1.data, -1))
queue = [root1]
# Traverse the first tree and mark nodes as visited
while queue:
curr = queue.pop(0)
if curr.left:
visited.add((curr.left.data, curr.data))
queue.append(curr.left)
if curr.right:
visited.add((curr.right.data, curr.data))
queue.append(curr.right)
# Use the helper function to check the second tree
return check_tree(root2, visited)
if __name__ == "__main__":
# Representation of input binary tree 1
# 1
# / \
# 2 3
# / \
# 4 5
# / \
# 7 8
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root1.left.right.left = Node(7)
root1.left.right.right = Node(8)
# Representation of input binary tree 2
# 1
# / \
# 3 2
# / / \
# 6 4 5
# / \
# 8 7
root2 = Node(1)
root2.left = Node(3)
root2.right = Node(2)
root2.left.left = Node(6)
root2.right.left = Node(4)
root2.right.right = Node(5)
root2.right.right.left = Node(8)
root2.right.right.right = Node(7)
if isIsomorphic(root1, root2):
print("Yes")
else:
print("No")
C#
// C# code to check if two trees are
// using Level Order Traversal
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Helper method to check if the second tree is isomorphic
static bool CheckTree(Node root2, HashSet<string> visited) {
if (!visited.Contains($"{root2.data},-1")) {
return false;
}
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root2);
while (queue.Count > 0) {
Node curr = queue.Dequeue();
if (curr.left != null) {
if (!visited.Contains(
$"{curr.left.data},{curr.data}")) {
return false;
}
queue.Enqueue(curr.left);
}
if (curr.right != null) {
if (!visited.Contains(
$"{curr.right.data},{curr.data}")) {
return false;
}
queue.Enqueue(curr.right);
}
}
return true;
}
// Main method to check if two trees are isomorphic
static bool isIsomorphic(Node root1, Node root2) {
HashSet<string> visited = new HashSet<string>();
// Mark the root of the first tree as visited
visited.Add($"{root1.data},-1");
Queue<Node> queue = new Queue<Node>();
queue.Enqueue(root1);
// Traverse the first tree and mark nodes as visited
while (queue.Count > 0) {
Node curr = queue.Dequeue();
if (curr.left != null) {
visited.Add($"{curr.left.data},{curr.data}");
queue.Enqueue(curr.left);
}
if (curr.right != null) {
visited.Add($"{curr.right.data},{curr.data}");
queue.Enqueue(curr.right);
}
}
// Use the helper method to check the second tree
return CheckTree(root2, visited);
}
static void Main(string[] args) {
// Representation of input binary tree 1
// 1
// / \
// 2 3
// / \
// 4 5
// / \
// 7 8
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.left.right.left = new Node(7);
root1.left.right.right = new Node(8);
// Representation of input binary tree 2
// 1
// / \
// 3 2
// / / \
// 6 4 5
// / \
// 8 7
Node root2 = new Node(1);
root2.left = new Node(3);
root2.right = new Node(2);
root2.left.left = new Node(6);
root2.right.left = new Node(4);
root2.right.right = new Node(5);
root2.right.right.left = new Node(8);
root2.right.right.right = new Node(7);
if (isIsomorphic(root1, root2)) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
}
JavaScript
// Javascript code to check if two trees are
// isomorphic using Level Order Traversal
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Helper function to check if the
// second tree is isomorphic
function CheckTree(root2, visited) {
// If the root of the second tree is not visited
if (visited.has(`${root2.data},-1`) === false) {
return false;
}
let q = [];
q.push(root2);
// Traverse the second tree
while (q.length > 0) {
let curr = q.shift();
if (curr.left) {
// If the left child has not been visited
if (visited.has(`${curr.left.data},
${curr.data}`) === false) {
return false;
}
q.push(curr.left);
}
if (curr.right) {
// If the right child has not been visited
if (visited.has(`${curr.right.data},
${curr.data}`) === false) {
return false;
}
q.push(curr.right);
}
}
return true;
}
// Main function to check if two trees are isomorphic
function isIsomorphic(root1, root2) {
let visited = new Set();
// Mark the root of the first tree as visited
visited.add(`${root1.data},-1`);
let q = [];
q.push(root1);
// Traverse the first tree and mark nodes as visited
while (q.length > 0) {
let curr = q.shift();
if (curr.left) {
visited.add(`${curr.left.data},${curr.data}`);
q.push(curr.left);
}
if (curr.right) {
visited.add(`${curr.right.data},${curr.data}`);
q.push(curr.right);
}
}
// Use the helper function to check the second tree
return CheckTree(root2, visited);
}
// Representation of input binary tree 1
// 1
// / \
// 2 3
// / \
// 4 5
// / \
// 7 8
const root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.left.right.left = new Node(7);
root1.left.right.right = new Node(8);
// Representation of input binary tree 2
// 1
// / \
// 3 2
// / / \
// 6 4 5
// / \
// 8 7
const root2 = new Node(1);
root2.left = new Node(3);
root2.right = new Node(2);
root2.left.left = new Node(6);
root2.right.left = new Node(4);
root2.right.right = new Node(5);
root2.right.right.left = new Node(8);
root2.right.right.right = new Node(7);
if (isIsomorphic(root1, root2)) {
console.log("Yes");
}
else {
console.log("No");
}
Time Complexity: O(n), where n is the total number of nodes in the larger tree. Each node is processed once.
Auxiliary Space: O(n)
Related article:
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