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

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.


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);
   cout << findDepthOfTree(root) << endl;
   return 0;


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



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