VOOZH about

URL: https://www.geeksforgeeks.org/dsa/height-n-ary-tree-parent-array-given/

⇱ Height of n-ary tree if parent array is given - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Height of n-ary tree if parent array is given

Last Updated : 9 May, 2024

Given a parent array P, where P[i] indicates the parent of the ith node in the tree(assume parent of root node id indicated with -1). Find the height of the tree.

Examples:

Input : array[] = [-1 0 1 6 6 0 0 2 7]
Output : height = 5
Tree formed is:
0
/ | \
5 1 6
/ | \
2 4 3
/
7
/
8
  1. Start at each node and keep going to its parent until we reach -1. 
  2. Also, keep track of the maximum height between all nodes.  

Implementation:


Output
Height of the given tree is: 5

Time Complexity : O( N^2 )
Auxiliary Space: O( 1 ) 

Optimized approach: We use dynamic programming. We store the height from root to each node in an array. So, if we know the height of the root to a node, then we can get the height from the root to the node child by simply adding 1. 

Implementation:


Output
Height of the given tree is: 5

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

Comment