Depth of an N-Ary tree in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to find the depth of the n-ary tree.

An n-ary tree is a tree in which each node of the tree has no more than n child nodes.

We have to find the depth of the n-ary tree. We will be using the vector to store the children of each node in the tree.

Let's see the steps to solve the problem.

  • Initialize the tree with dummy data.

  • Write a recursive function to find the depth of the n-ary tree.

    • Initialize a variable to store the max depth of the tree.

    • Iterate over the children of each node.

      • The max depth is the max of the current max depth and the depth of the node children.

      • If we assume the max depth variable is maxDepth and maxDepth = max(maxDepth, findDepthOfTree(*children) is the recursive statement to find the depth of the tree.

    • The final maximum depth of the tree is maxDepth + 1.

  • Print the max depth of the tree.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   vector<Node *> child;
};
Node *newNode(int data) {
   Node *temp = new Node;
   temp->data = data;
   return temp;
}
int findDepthOfTree(struct Node *node) {
   if (node == NULL) {
      return 0;
   }
   int maxDepth = 0;
   for (vector<Node*>::iterator it = node->child.begin(); it != node->child.end(); it++) {
      maxDepth = max(maxDepth, findDepthOfTree(*it));
   }
   return maxDepth + 1;
}
int main() {
   Node *root = newNode(1);
   root->child.push_back(newNode(2));
   root->child.push_back(newNode(3));
   root->child.push_back(newNode(4));
   root->child[2]->child.push_back(newNode(1));
   root->child[2]->child.push_back(newNode(2));
   root->child[2]->child.push_back(newNode(3));
   root->child[2]->child.push_back(newNode(4));
   cout << findDepthOfTree(root) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

3

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 27-Jan-2021 12:22:00
Advertisements