VOOZH about

URL: https://www.geeksforgeeks.org/dsa/iterative-approach-to-check-if-two-binary-trees-are-isomorphic-or-not/

⇱ Iterative Approach to check if two Binary Trees are Isomorphic or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 Tree-Isomorphism-Problem

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:


Output
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:

Comment
Article Tags: