
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Depth of an N-ary Tree in C++
Let us first define the struct that would represent a tree node that contains a character key and a vector of Node *.
struct Node{ char key; vector<Node *> children; };
Next we create our createNode(int key) function that takes an int key value and assign it to the key member of the node. The function returns the pointer to the created struct node.
Node *createNode(int key){ Node *node = new Node; node->key = key; return node; }
Our depthOfTree(struct Node* root) function takes the root node as parameter. If the root is NULL then the depth is returned as 0.
int depthOfTree(struct Node *root){ if (root==NULL) return 0;
We then define maxDepth variable and assign its value to 0. We then iterate over all the children of the tree and increment maxDepth on each recursion. Once the base condition is met and the recursion is over we then return the maxDepth.
int depthOfTree(struct Node *root){ if (root==NULL) return 0; int maxDepth = 0; for(auto i: root->children){ maxDepth = depthOfTree(i) + 1; } return maxDepth; }
Example
Let us look at the following implementation to find the depth of the N-Ary tree −
#include <iostream> #include <vector> using namespace std; struct Node{ char key; vector<Node *> children; }; Node *createNode(int key){ Node *node = new Node; node->key = key; return node; } int depthOfTree(struct Node *root){ if (root==NULL) return 0; int maxDepth = 0; for(auto i: root->children){ maxDepth = depthOfTree(i) + 1; } return maxDepth; } int main(){ Node *root = createNode('S'); (root->children).push_back(createNode('O')); (root->children).push_back(createNode('A')); (root->children).push_back(createNode('D')); (root->children).push_back(createNode('N')); (root->children[0]->children).push_back(createNode('L')); (root->children[0]->children).push_back(createNode('I')); (root->children[2]->children).push_back(createNode('R')); (root->children[3]->children).push_back(createNode('C')); (root->children[3]->children).push_back(createNode('H')); (root->children[3]->children).push_back(createNode('I')); cout <<"The depth of the n-ary tree is "<< depthOfTree(root) << endl; return 0; }
Output
The above code will produce the following output −
The depth of the n-ary tree is 2