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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Isomorphism in N-ary Trees
- Custom Tree Problem
- The Great Tree-List Recursion Problem.
- Applications of Minimum Spanning Tree Problem
- Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
- Nuts & Bolts Problem (Lock & Key problem) | Set 1
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Convert a given Binary tree to a tree that holds Logical OR property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Convert a given Binary tree to a tree that holds Logical AND property
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Sub-tree with minimum color difference in a 2-coloured tree