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.
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.