Open In App

Height of n-ary tree if parent array is given

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:

C++





Java





Python3





C#





Javascript





Output: 

Height of the given tree is: 5

 

Time Complexity : O( N^2 )

Space Complexity : 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:

CPP





Java




// Java program to find the height of the generic
// tree(n-ary tree) if parent array is given
 
import java.io.*;
import java.util.*;
 
class GFG {
     
    // function to fill the height vector
    static int rec(int i, int parent[], int[] height)
    {
        // if we have reached root node the
    // return 1 as height of root node
    if (parent[i] == -1) {
        return 1;
    }
   
    // if we have calculated height of a
    // node then return if
    if (height[i] != -1) {
        return height[i];
    }
  
    // height from root to a node = height
    // from root to nodes parent + 1
    height[i] = rec(parent[i], parent, height) + 1;
     
    // return nodes height
    return height[i];
    }
     
     
    // function to find the height of tree
    static int findHeight(int[] parent, int n)
    {
        int res = 0;
  
    // vector to store heights of all nodes
    int height[]=new int[n];
    Arrays.fill(height,-1);
  
    for (int i = 0; i < n; i++) {
        res = Math.max(res, rec(i, parent, height));
    }
  
    return res;
    }
     
    // Driver program
     
    public static void main (String[] args) {
         
        int[] parent = { -1, 0, 1, 6, 6, 0, 0, 2, 7 };
        int n = parent.length;
        int height = findHeight(parent, n);
         
         
        System.out.println("Height of the given tree is: "+height);
    }
}
 
// This code is contributed by avanitrachhadiya2155


Python3





C#





Javascript





Output: 

Height of the given tree is: 5

 

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



Last Updated : 08 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads