Note: The count of all ways to traverse is the product of factorials of the number of children of each node. Refer to the below figure for a clear understanding:
Here, ‘A’ has four children, so 4! permutations possible ‘B’ has two children, so 2! permutations possible ‘F’ has no children, so 0! permutations possible ….. And so on Hence all such ways are- 4 ! * 2 ! * 0 ! * 1 ! * 3 ! * 2 ! * 0 ! * 0 ! * 0 ! * 0 ! * 1 ! * 0 ! * 0 ! = 576 way That’s a huge number of ways and among them, only few prove to be useful, like- inorder, level-order, preorder, and postorder (arranged according to the popularity of these traversals)
Follow the below steps to solve the problem:
Initialize ways equal to one and create a queue of type Node and push root into it
While the queue is not empty
Initialize integer p equal to the front Node of the queue
Set ways equal to ways * x!, where x is the count of p’s children
Enqueue all the children of the Node p
Below is the implementation of the above approach:
// C++ program to find the number of ways to traverse a
// n-ary tree starting from the root node
// Structure of a node of an n-ary tree
// Utility function to create a new tree node
Node* temp = newNode;
temp->key = key;
// Utility Function to find factorial of given number
if(n == 0)
returnn * factorial(n - 1);
// Function to calculate the number of ways of traversing
// the n-ary starting from root.
// This function is just a modified breadth-first search.
// We can use a depth-first search too.
intways = 1; // Initialize result
// If the tree is empty there is no way of traversing
Time Complexity: O(N2). We can optimize the solution to work in O(N) time by per-computing factorials of all numbers from 1 to N Auxiliary Space: O(N)
Common Pitfalls: Since products of factorials can tend to grow very huge, so it may overflow. It is preferable to use data types like- unsigned long long int in C/C++, as the number of ways can never be a negative number. In Java and Python, there are Big Integers to take care of overflows
This article is contributed by Rachit Belwariar. 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.
Please Login to comment...