Given a tree of size n as array parent[0..n-1] where every index i in the parent[] represents a node and the value at i represents the immediate parent of that node. For root, the node value will be -1. Find the height of the generic tree given the parent links.
Here, a generic tree is sometimes also called an N-ary tree or N-way tree where N denotes the maximum number of child a node can have. In this problem, the array represents n number of nodes in the tree.
The naive approach is to traverse up the tree from the node till the root node is reached with node value -1. While Traversing for each node stores maximum path length. The Time Complexity of this solution is O(n^2).
[Expected Approach - 1] Using BFS - O(n) Time and O(n) Space
Build graph for N-ary Tree in O(n) time and apply BFS on the stored graph in O(n) time and while doing BFS store maximum reached level. This solution does two iterations to find the height of N-ary tree.
Below is the implementation of the above approach:
Output
2
[Expected Approach - 2] Without using map - O(n) Time and O(n) Space
We can find the height of the N-ary Tree in only one iteration. We visit nodes from 0 to n-1 iteratively and mark the unvisited ancestors recursively if they are not visited before till we reach a node which is visited, or we reach the root node. If we reach the visited node while traversing up the tree using parent links, then we use its height and will not go further in recursion.