VOOZH about

URL: https://www.geeksforgeeks.org/dsa/tree-isomorphism-problem/

⇱ Tree Isomorphism Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tree Isomorphism Problem

Last Updated : 23 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. 

[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space

The idea is to traverse both trees recursively, comparing the nodes n1 and n2. Their data must be the same, and their subtrees must either be identical or mirror images (flipped). This ensures that the trees are structurally isomorphic.

Follow the steps to solve the problem:

Let the current internal nodes of the two trees be n1 and n2. For the subtrees rooted at n1 and n2 to be isomorphic, the following conditions must hold:

  • The data of n1 and n2 must be the same.
  • One of the following two conditions must be true for the children of n1 and n2:
    • The left child of n1 is isomorphic to the left child of n2, and the right child of n1 is isomorphic to the right child of n2.
    • The left child of n1 is isomorphic to the right child of n2, and the right child of n1 is isomorphic to the left child of n2.
  • This ensures that the trees are either structurally identical or have been "flipped" at some levels while still being isomorphic.

Below is the implementation of the above approach:


Output
False

Time Complexity:O(n), because each node in both trees is visited once during the isomorphism check, where n is the total number of nodes in the trees.
Auxiliary Space:O(h), due to the recursion stack, where h is the height of the trees; in the worst case, this can be O(n) for skewed trees.

[Expected Approach - 2] Using Iteration - O(n) Time and O(n) Space

To solve the question mentioned above we traverse both the trees iteratively using level order traversal and store the levels in a queue data structure. There are following two conditions at each level

  • The value of nodes has to be the same.
  • The number of nodes at each level should be the same.

Please refer to Iterative Approach to check if two Binary Trees are Isomorphic or not for implementation.

Comment
Article Tags: