Iterative Approach to check if two Binary Trees are Isomorphic or not
Last Updated :
04 Oct, 2024
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
Iterative approach to check if a Binary Tree is BST or not Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: YES Explanation: Since the left subtree of each node of the tree consists of s
9 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one ch
8 min read
Iterative approach to check if a Binary Tree is Perfect Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.A Binary tree is a Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : Yes Input : 20 / \ 8
9 min read
Check if two binary trees are mirror | Set 3 Given two arrays, A[] and B[] consisting of M pairs, representing the edges of the two binary trees of N distinct nodes according to the level order traversal, the task is to check if trees are the mirror images of each other. Examples: Input: N = 6, M = 5, A[][2] = {{1, 5}, {1, 4}, {5, 7}, {5, 8},
10 min read
Check for Symmetric Binary Tree (Iterative Approach Using Queue) Given a binary tree, the task is to check whether it is a mirror of itself.Examples: Input: Output: TrueExplanation: As the left and right half of the above tree is mirror image, tree is symmetric. Input: Output: FalseExplanation: As the left and right half of the above tree is not the mirror image,
8 min read