Given an n-ary tree containing positive node values, the task is to find the depth of the tree. Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multiple branches or children for each node.
Examples:
Input:
Output: 3 Explanation: The longest path from the root (node 81) to a leaf is either 81 -> 26 -> 95 or 81 -> 26 -> 86, giving a maximum depth of 3.
Input:
Output: 2 Explanation: The longest path from the root (node 4) to any leaf (nodes 5 or 7) is 2, as it only requires two levels of traversal.
Approach:
The idea is to calculate the depth of an N-ary tree recursively, initialize the maximum depth as 0, then recursively calculate the depth for each child and keep track of the highest depth encountered. Finally, add 1 to the maximum depth (for the current node) and return the result. This approach ensures that we find the longest path from the root to any leaf node.
N-Ary tree can be traversed just like a normal tree. We just have to consider all children of a given node and recursively call that function on every node.
C++
// C++ Code to find the depth of an N-ary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;vector<Node*>children;Node(intval){data=val;}};// Recursive function to calculate maximum depthintmaxDepth(Node*root){// If the node is null, depth is 0if(!root){return0;}intdepth=0;// Recur for all children and find the maximum depthfor(autochild:root->children){depth=max(depth,maxDepth(child));}// Add 1 to include the current node// in the depth countreturndepth+1;}intmain(){// Representation of given N-ary tree// 1// / | \ // 2 3 4// / \ // 5 6Node*root=newNode(1);root->children.push_back(newNode(2));root->children.push_back(newNode(3));root->children.push_back(newNode(4));root->children[0]->children.push_back(newNode(5));root->children[2]->children.push_back(newNode(6));cout<<maxDepth(root);return0;}
Java
// Java Code to find the depth of an N-ary treeimportjava.util.*;classNode{intdata;List<Node>children;Node(intval){data=val;children=newArrayList<>();}}// Recursive function to calculate// maximum depthclassGfG{staticintmaxDepth(Noderoot){// If the node is null, depth is 0if(root==null){return0;}intdepth=0;// Recur for all children and find// the maximum depthfor(Nodechild:root.children){depth=Math.max(depth,maxDepth(child));}// Add 1 to include the current node // in the depth countreturndepth+1;}publicstaticvoidmain(String[]args){// Representation of given N-ary tree// 1// / | \// 2 3 4// / \// 5 6Noderoot=newNode(1);root.children.add(newNode(2));root.children.add(newNode(3));root.children.add(newNode(4));root.children.get(0).children.add(newNode(5));root.children.get(2).children.add(newNode(6));System.out.println(maxDepth(root));}}
Python
# Python Code to find the depth # of an N-ary treeclassNode:def__init__(self,val):self.data=valself.children=[]# Recursive function to calculate# maximum depthdefmax_depth(root):# If the node is None, depth is 0ifnotroot:return0depth=0# Recur for all children and # find the maximum depthforchildinroot.children:depth=max(depth,max_depth(child))# Add 1 to include the current# node in the depth countreturndepth+1if__name__=="__main__":# Representation of given N-ary tree# 1# / | \# 2 3 4# / \# 5 6root=Node(1)root.children.append(Node(2))root.children.append(Node(3))root.children.append(Node(4))root.children[0].children.append(Node(5))root.children[2].children.append(Node(6))print(max_depth(root))
C#
// C# Code to find the depth of an N-ary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicList<Node>children;publicNode(intval){data=val;children=newList<Node>();}}// Recursive function to calculate// maximum depthclassGfG{staticintMaxDepth(Noderoot){// If the node is null, depth is 0if(root==null){return0;}intdepth=0;// Recur for all children and find the maximum depthforeach(Nodechildinroot.children){depth=Math.Max(depth,MaxDepth(child));}// Add 1 to include the current// node in the depth countreturndepth+1;}staticvoidMain(string[]args){// Representation of given N-ary tree// 1// / | \// 2 3 4// / \// 5 6Noderoot=newNode(1);root.children.Add(newNode(2));root.children.Add(newNode(3));root.children.Add(newNode(4));root.children[0].children.Add(newNode(5));root.children[2].children.Add(newNode(6));Console.WriteLine(MaxDepth(root));}}
JavaScript
// JavaScript Code to find the depth // of an N-ary treeclassNode{constructor(val){this.data=val;this.children=[];}}// Recursive function to calculate // maximum depthfunctionmaxDepth(root){// If the node is null, depth is 0if(!root){return0;}letdepth=0;// Recur for all children and find// the maximum depthfor(letchildofroot.children){depth=Math.max(depth,maxDepth(child));}// Add 1 to include the current node // in the depth countreturndepth+1;}// Representation of given N-ary tree// 1// / | \// 2 3 4// / \// 5 6constroot=newNode(1);root.children.push(newNode(2));root.children.push(newNode(3));root.children.push(newNode(4));root.children[0].children.push(newNode(5));root.children[2].children.push(newNode(6));console.log(maxDepth(root));
Output
3
Time Complexity: O(n), since each node is visited once, where n is the total number of nodes in the N-ary tree. Auxiliary Space: O(h), where h is the height of the tree, due to recursive call stack usage.