Depth of an N-Ary tree - GeeksforGeeks

28 Jun, 2021
Given an N-Ary tree, find depth of the tree. An N-Ary tree is a tree in which nodes can have at most N children.Examples: Example 1:  
Example 2:  
 
N-Ary tree can be traversed just like a normal tree. We just have to consider all childs of a given node and recursively call that function on every node.  
C++
Java
C#
Javascript
// C++ program to find the height of// an N-ary tree#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node{   char key;   vector<Node *> child;}; // Utility function to create a new tree nodeNode *newNode(int key){   Node *temp = new Node;   temp->key = key;   return temp;} // Function that will return the depth// of the treeint depthOfTree(struct Node *ptr){    // Base case    if (!ptr)        return 0;     // Check for all children and find    // the maximum depth    int maxdepth = 0;    for (vector<Node*>::iterator it = ptr->child.begin();                              it != ptr->child.end(); it++)        maxdepth = max(maxdepth, depthOfTree(*it));     return maxdepth + 1 ;} // Driver programint 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 << depthOfTree(root) << endl;    return 0;}
// Java program to find the height of// an N-ary treeimport java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{    char key;    Vector<Node > child;}; // Utility function to create a new tree nodestatic Node newNode(int key){    Node temp = new Node();    temp.key = (char) key;    temp.child = new Vector<Node>();    return temp;} // Function that will return the depth// of the treestatic int depthOfTree(Node ptr){    // Base case    if (ptr == null)        return 0;     // Check for all children and find    // the maximum depth    int maxdepth = 0;    for (Node it : ptr.child)        maxdepth = Math.max(maxdepth,                            depthOfTree(it));     return maxdepth + 1 ;} // Driver Codepublic static void main(String[] args){    /* 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).add(newNode('B'));    (root.child).add(newNode('F'));    (root.child).add(newNode('D'));    (root.child).add(newNode('E'));    (root.child.get(0).child).add(newNode('K'));    (root.child.get(0).child).add(newNode('J'));    (root.child.get(2).child).add(newNode('G'));    (root.child.get(3).child).add(newNode('C'));    (root.child.get(3).child).add(newNode('H'));    (root.child.get(3).child).add(newNode('I'));    (root.child.get(0).child.get(0).child).add(newNode('N'));    (root.child.get(0).child.get(0).child).add(newNode('M'));    (root.child.get(3).child.get(2).child).add(newNode('L'));         System.out.print(depthOfTree(root) + "\n");}} // This code is contributed by Rajput-Ji
// C# program to find the height of// an N-ary treeusing System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treepublic class Node{    public char key;    public List<Node > child;}; // Utility function to create a new tree nodestatic Node newNode(int key){    Node temp = new Node();    temp.key = (char) key;    temp.child = new List<Node>();    return temp;} // Function that will return the depth// of the treestatic int depthOfTree(Node ptr){    // Base case    if (ptr == null)        return 0;     // Check for all children and find    // the maximum depth    int maxdepth = 0;    foreach (Node it in ptr.child)        maxdepth = Math.Max(maxdepth,                            depthOfTree(it));     return maxdepth + 1 ;} // Driver Codepublic static void Main(String[] args){         /* 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).Add(newNode('B'));    (root.child).Add(newNode('F'));    (root.child).Add(newNode('D'));    (root.child).Add(newNode('E'));    (root.child[0].child).Add(newNode('K'));    (root.child[0].child).Add(newNode('J'));    (root.child[2].child).Add(newNode('G'));    (root.child[3].child).Add(newNode('C'));    (root.child[3].child).Add(newNode('H'));    (root.child[3].child).Add(newNode('I'));    (root.child[0].child[0].child).Add(newNode('N'));    (root.child[0].child[0].child).Add(newNode('M'));    (root.child[3].child[2].child).Add(newNode('L'));         Console.Write(depthOfTree(root) + "\n");}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find the height of// an N-ary tree // Structure of a node of an n-ary treeclass Node{    constructor()    {        this.key = 0;        this.child = [];    }}; // Utility function to create a new tree nodefunction newNode(key){    var temp = new Node();    temp.key =  key;    temp.child = [];    return temp;} // Function that will return the depth// of the treefunction depthOfTree(ptr){    // Base case    if (ptr == null)        return 0;     // Check for all children and find    // the maximum depth    var maxdepth = 0;    for(var it of ptr.child)        maxdepth = Math.max(maxdepth,                            depthOfTree(it));     return maxdepth + 1 ;} // Driver Code /* Let us create below tree*             A*         / / \ \*     B F D E*     / \ | /|\*     K J G C H I*     /\         \* N M         L*/var root = newNode('A');(root.child).push(newNode('B'));(root.child).push(newNode('F'));(root.child).push(newNode('D'));(root.child).push(newNode('E'));(root.child[0].child).push(newNode('K'));(root.child[0].child).push(newNode('J'));(root.child[2].child).push(newNode('G'));(root.child[3].child).push(newNode('C'));(root.child[3].child).push(newNode('H'));(root.child[3].child).push(newNode('I'));(root.child[0].child[0].child).push(newNode('N'));(root.child[0].child[0].child).push(newNode('M'));(root.child[3].child[2].child).push(newNode('L'));document.write(depthOfTree(root) + "<br>");  </script>
Output:  
4
 
YouTubeGeeksforGeeks507K subscribersDepth of an N-Ary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=x_hJLIOIqa8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
Rajput-Ji
itsok
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Introduction to Tree Data Structure
Expression Tree
Lowest Common Ancestor in a Binary Tree | Set 1
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Deletion in a Binary Tree
Binary Tree (Array implementation)