Isomorphism in N-ary Trees

• Difficulty Level : Hard
• Last Updated : 24 Nov, 2021

Given two N-ary trees having M nodes each. Also, given their edges and their roots respectively. The task is to check if they are isomorphic trees or not. If both the trees are isomorphic then print “Yes” else print “No”.
Examples:

Input: M = 9, Root Node of tree-1: 1, Root Node of tree-2: 3
Edges of Tree-1: { (1, 3), (3, 4), (3, 5), (1, 8), (8, 9), (1, 2), (2, 6), (2, 7) }
Edges of Tree-2: { (3, 1), (1, 2), (1, 5), (3, 6), (6, 7), (3, 4), (4, 8), (4, 9) } Output: YES
Input: M = 9, Root Node of tree-1: 6, Root Node of tree-2: 7
Edges of Tree-1: {(1, 3),(1, 2), (1, 8), (3, 4), (3, 5), (8, 9), (2, 6), (2, 7)}
Edges of Tree-2: {(1, 2), (1, 5), (3, 1), (3, 4), (4, 8), (4, 9), (6, 3), (7, 6)} Output: NO

Approach:
The idea is to find out the canonical form of both the trees and comparing them. The leaf node will return “()” to its subsequent upper levels.
Below is the example showing the process of finding the canonical form. Below is the implementation of the above approach: