VOOZH about

URL: https://www.geeksforgeeks.org/dsa/depth-n-ary-tree/

⇱ Depth of an N-Ary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Depth of an N-Ary tree

Last Updated : 29 Oct, 2024

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:

👁 second-largest-element-in-n-ary-tree-2

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:

👁 minimum-operation-to-make-every-leaf-node-equal-2

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. 


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.

Comment
Article Tags:
Article Tags: