Open In App

Depth of an N-Ary tree

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Algorithm

Here is the algorithm for finding the depth of an N-Ary tree:

1)Define a struct for the nodes of the N-ary tree with a key and a vector of pointers to its child nodes.
2)Create a utility function to create a new node with the given key.
3)Define a function depthOfTree that takes in a pointer to a Node and returns the depth of the tree.
4)If the pointer to the Node is null, return 0.
5)Initialize a variable maxdepth to 0.
6)Iterate through the vector of child nodes of the current Node and for each child node, recursively call depthOfTree function on the child and find the maximum depth.
7)Update the maxdepth variable to be the maximum of the current maxdepth and the depth of the child node.
8)Return the maxdepth plus 1 as the depth of the tree.
9)In the main function, create an N-ary tree and call depthOfTree function on the root node of the tree to get the depth.
10)Print the depth of the tree.

Examples:

  • Example 1: 
     

narry1

  • Example 2: 
     

nary2

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. 

Implementation:

C++




// 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 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;
}
  
// Function that will return the depth
// of the tree
int 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 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 << depthOfTree(root) << endl;
  
   return 0;
}


Java




// Java program to find the height of
// an N-ary tree
import java.util.*;
  
class GFG
{
  
// Structure of a node of an n-ary tree
static class Node
{
    char key;
    Vector<Node > child;
};
  
// Utility function to create a new tree node
static 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 tree
static 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 Code
public 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


Python3




# Python program to find the height of
# an N-ary tree
  
# Structure of a node of an n-ary tree
class Node:
    def __init__(self, key):
        self.key = key
        self.child = []
  
# Utility function to create a new tree node
def new_node(key):
    temp = Node(key)
    return temp
  
# Function that will return the depth
# of the tree
def depth_of_tree(ptr):
    # Base case
    if ptr is None:
        return 0
  
    # Check for all children and find
    # the maximum depth
    maxdepth = 0
    for child in ptr.child:
        maxdepth = max(maxdepth, depth_of_tree(child))
  
    return maxdepth + 1
  
# Driver program
if __name__ == '__main__':
    """ Let us create below tree
            A
        / / \ \
        B F D E
        / \ | /|\
        K J G C H I
        /\         \
        N M         L
    """
  
    root = new_node('A')
    root.child.extend([new_node('B'), new_node('F'), new_node('D'), new_node('E')])
    root.child[0].child.extend([new_node('K'), new_node('J')])
    root.child[2].child.append(new_node('G'))
    root.child[3].child.extend([new_node('C'), new_node('H'), new_node('I')])
    root.child[0].child[0].child.extend([new_node('N'), new_node('M')])
    root.child[3].child[2].child.append(new_node('L'))
  
    print(depth_of_tree(root))


C#




// C# program to find the height of
// an N-ary tree
using System;
using System.Collections.Generic;
  
class GFG
{
  
// Structure of a node of an n-ary tree
public class Node
{
    public char key;
    public List<Node > child;
};
  
// Utility function to create a new tree node
static 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 tree
static 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 Code
public 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


Javascript




<script>
  
// JavaScript program to find the height of
// an N-ary tree
  
// Structure of a node of an n-ary tree
class Node
{
    constructor()
    {
        this.key = 0;
        this.child = [];
    }
};
  
// Utility function to create a new tree node
function newNode(key)
{
    var temp = new Node();
    temp.key =  key;
    temp.child = [];
    return temp;
}
  
// Function that will return the depth
// of the tree
function 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

Time complexity: O(n)
Auxiliary Space: O(n)

 



Previous Article
Next Article

Similar Reads

Minimum valued node having maximum depth in an N-ary Tree
Given a tree of N nodes, the task is to find the node having maximum depth starting from the root node, taking the root node at zero depth. If there are more than 1 maximum depth node, then find the one having the smallest value. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 4 Explanation: For this tree: Height of Node 1 - 0, Height of Node 2 - 1, Hei
5 min read
Replace every node with depth in N-ary Generic Tree
Given an array arr[] representing a Generic(N-ary) tree. The task is to replace the node data with the depth(level) of the node. Assume level of root to be 0. Array Representation: The N-ary tree is serialized in the array arr[] using level order traversal as described below:   The input is given as a level order traversal of N-ary Tree.The first e
15+ min read
Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries. Why do we need a segment tree when we already have an n-ary rooted tree? Many times, a situation occurs where the same ope
15+ min read
Check if the given n-ary tree is a binary tree
Given an n-ary tree, the task is to check whether the given tree is binary or not. Examples: Input: A / \ B C / \ \ D E F Output: Yes Input: A / | \ B C D \ F Output: No Approach: Every node in a binary tree can have at most 2 children. So, for every node of the given tree, count the number of children and if for any node the count exceeds 2 then p
6 min read
Remove all leaf nodes from a Generic Tree or N-ary Tree
Given a Generic tree, the task is to delete the leaf nodes from the tree. Examples: Input: 5 / / \ \ 1 2 3 8 / / \ \ 15 4 5 6 Output: 5 : 1 2 3 1 : 2 : 3 : Explanation: Deleted leafs are: 8, 15, 4, 5, 6 Input: 8 / | \ 9 7 2 / | \ | / / | \ \ 4 5 6 10 11 1 2 2 3 Output: 8: 9 7 2 9: 7: 2: Approach: Follow the steps given below to solve the problem Co
9 min read
Count of nodes in given N-ary tree such that their subtree is a Binary Tree
Given an N-ary tree root, the task is to find the count of nodes such that their subtree is a binary tree. Example: Input: Tree in the image below Output: 11Explanation: The nodes such that there subtree is a binary tree are {2, 8, 10, 6, 7, 3, 1, 9, 5, 11, 12}. Input: Tree in the image below Output: 9 Approach: The given problem can be solved by u
11 min read
Tree of Space - Locking and Unlocking N-Ary Tree
Given a world map in the form of Generic M-ary Tree consisting of N nodes and an array queries[], the task is to implement the functions Lock, Unlock and Upgrade for the given tree. For each query in queries[], the functions return true when the operation is performed successfully, otherwise it returns false. The functions are defined as: X: Name o
10 min read
Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from the root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22 Approach: There exists a recursive approach to this problem. This can also be so
8 min read
Sum of nodes at maximum depth of a Binary Tree | Set 2
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 In the previous article we discussed a recursive solution which first finds the maximum
7 min read
Find the Maximum Depth or Height of given Binary Tree
Given a binary tree, the task is to find the height of the tree. The height of the tree is the number of vertices in the tree from the root to the deepest node. Note: The height of an empty tree is 0 and the height of a tree with single node is 1. Recommended PracticeHeight of Binary TreeTry It!Recursively calculate the height of the left and the r
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg