Write a function to detect if two trees are isomorphic. Two trees are called isomorphic if one of them can be obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.
We simultaneously traverse both trees. Let the current internal nodes of two trees being traversed be n1 and n2 respectively. There are following two conditions for subtrees rooted with n1 and n2 to be isomorphic.
1) Data of n1 and n2 is same.
2) One of the following two is true for children of n1 and n2
……a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to right child of n2.
……b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic to left child of n2.
Time Complexity: The above solution does a traversal of both trees. So time complexity is O(min(m,n)*2) or O(min(m,n)) where m and n are number of nodes in given trees.
This article is contributed by Ciphe. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Nuts & Bolts Problem (Lock & Key problem) | Set 1
- Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
- Convert a Binary Tree into its Mirror Tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Convert a given tree to its Sum Tree
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- The Knight's tour problem | Backtracking-1
- N Queen Problem | Backtracking-3
- Activity Selection Problem | Greedy Algo-1
- The Celebrity Problem
- Word Wrap Problem | DP-19
- Partition problem | DP-18
- Box Stacking Problem | DP-22
- Subset Sum Problem | DP-25
- The Stock Span Problem
- Word Break Problem | DP-32
- Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
- Printing brackets in Matrix Chain Multiplication Problem
- Boolean Parenthesization Problem | DP-37