Given an n-ary tree, count number of ways to traverse an n-ary (or a Directed Acyclic Graph) tree starting from the root vertex.
Suppose we have a given N-ary tree as shown below.
Now we have to find the number of ways of traversing the whole tree starting from the root vertex. There can be many such ways. Some of them are listed below.
1) N->M->K->J->B->F->D->E->C->H->I->L->A (kind-of depth first traversal).
2) A->B->F->D->E->K->J->G->C->H->I->N->M->L (level order traversal)
3) ………
4) ………
.
.
.
and so on….
We strongly recommend you to minimize your browser and try this yourself first.
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 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 proves to be useful, like- inorder, level-order, preorder, postorder (arranged according to the popularity of these traversals)
// C++ program to find the number of ways to traverse a // n-ary tree starting from the root node #include <bits/stdc++.h> using namespace std; // Structure of a node of an n-ary tree struct Node { char key; vector<Node *> child; }; // Utility function to create a new tree node Node *newNode(int key) { Node *temp = new Node; temp->key = key; return temp; } // Untility Function to find factorial of given number int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } // Function to calculate the number of ways of travesing // the n-ary starting from root. // This function is just a modified breadth-first search. // We can use a depth-first search too. int calculateWays(Node * root) { int ways = 1; // Initialize result // If the tree is empty there is no way of traversing // the tree. if (root == NULL) return 0; // Create a queue and enqueue root to it. queue<Node *>q; q.push(root); // Level order traversal. while (!q.empty()) { // Dequeue an item from queue and print it Node * p = q.front(); q.pop(); // The number of ways is the product of // factorials of number of children of each node. ways = ways*(factorial(p->child.size())); // Enqueue all childrent of the dequeued item for (int i=0; i<p->child.size(); i++) q.push(p->child[i]); } return(ways); } // Driver program int main() { /* Let us create below tree * A * / / \ \ * B F D E * / \ | /|\ * K J G C H I * /\ \ * N M L */ Node *root = newNode('A'); (root->child).push_back(newNode('B')); (root->child).push_back(newNode('F')); (root->child).push_back(newNode('D')); (root->child).push_back(newNode('E')); (root->child[0]->child).push_back(newNode('K')); (root->child[0]->child).push_back(newNode('J')); (root->child[2]->child).push_back(newNode('G')); (root->child[3]->child).push_back(newNode('C')); (root->child[3]->child).push_back(newNode('H')); (root->child[3]->child).push_back(newNode('I')); (root->child[0]->child[0]->child).push_back(newNode('N')); (root->child[0]->child[0]->child).push_back(newNode('M')); (root->child[3]->child[2]->child).push_back(newNode('L')); cout << calculateWays(root); ; return 0; } |
Output :
576
Time Complexity: We visit each node once during the level order traversal and take O(n) time to compute factorial for every node. Total time taken is O(Nn) where N = number of nodes in the n-ary tree. We can optimize the solution to work in O(N) time by per-computing factorials of all numbers from 1 to n.
Auxiliary Space : Since we are only using a queue and a structure for every node, so overall space complexity is also 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 Integer 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 contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
Recommended Posts:
- Number of ways to divide a Binary tree into two halves
- Number of ways to paint a tree of N nodes with K distinct colors with given conditions
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Ways to color a skewed tree such that parent and child have different colors
- Number of ways to change the Array such that largest element is LCM of array
- Convert a Binary Tree into its Mirror Tree
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- 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 given Binary Tree is height balanced like a Red-Black Tree
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap



