Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Find Height of Binary Tree represented by Parent array

  • Difficulty Level : Hard
  • Last Updated : 07 Sep, 2021

A given array represents a tree in such a way that the array value gives the parent node of that particular index. The value of the root node index would always be -1. Find the height of the tree. 
The height of a Binary Tree is the number of nodes on the path from the root to the deepest leaf node, and the number includes both root and leaf. 
 

Input: parent[] = {1 5 5 2 2 -1 3}
Output: 4
The given array represents following Binary Tree 
         5
        /  \
       1    2
      /    / \
     0    3   4
         /
        6 


Input: parent[] = {-1, 0, 0, 1, 1, 3, 5};
Output: 5
The given array represents following Binary Tree 
         0
       /   \
      1     2
     / \
    3   4
   /
  5 
 /
6

Recommended: Please solve it on “PRACTICE ” first before moving on to the solution. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Source: Amazon Interview experience | Set 128 (For SDET)
We strongly recommend minimizing your browser and try this yourself first.
A simple solution is to first construct the tree and then find the height of the constructed binary tree. The tree can be constructed recursively by first searching the current root, then recurring for the found indexes and making them left and right subtrees of the root. This solution takes O(n2) as we have to search for every node linearly.
An efficient solution can solve the above problem in O(n) time. The idea is to first calculate the depth of every node and store it in an array depth[]. Once we have the depths of all nodes, we return the maximum of all depths. 
1) Find the depth of all nodes and fill in an auxiliary array depth[]. 
2) Return maximum value in depth[].
Following are steps to find the depth of a node at index i. 
1) If it is root, depth[i] is 1. 
2) If depth of parent[i] is evaluated, depth[i] is depth[parent[i]] + 1. 
3) If depth of parent[i] is not evaluated, recur for parent and assign depth[i] as depth[parent[i]] + 1 (same as above).
Following is the implementation of the above idea.
 

C++




// C++ program to find height using parent array
#include <bits/stdc++.h>
using namespace std;
 
// This function fills depth of i'th element in parent[].
// The depth is filled in depth[i].
void fillDepth(int parent[], int i, int depth[])
{
    // If depth[i] is already filled
    if (depth[i])
        return;
 
    // If node at index i is root
    if (parent[i] == -1) {
        depth[i] = 1;
        return;
    }
 
    // If depth of parent is not evaluated before, then
    // evaluate depth of parent first
    if (depth[parent[i]] == 0)
        fillDepth(parent, parent[i], depth);
 
    // Depth of this node is depth of parent plus 1
    depth[i] = depth[parent[i]] + 1;
}
 
// This function returns height of binary tree represented
// by parent array
int findHeight(int parent[], int n)
{
    // Create an array to store depth of all nodes/ and
    // initialize depth of every node as 0 (an invalid
    // value). Depth of root is 1
    int depth[n];
    for (int i = 0; i < n; i++)
        depth[i] = 0;
 
    // fill depth of all nodes
    for (int i = 0; i < n; i++)
        fillDepth(parent, i, depth);
 
    // The height of binary tree is maximum of all depths.
    // Find the maximum value in depth[] and assign it to
    // ht.
    int ht = depth[0];
    for (int i = 1; i < n; i++)
        if (ht < depth[i])
            ht = depth[i];
    return ht;
}
 
// Driver program to test above functions
int main()
{
    // int parent[] = {1, 5, 5, 2, 2, -1, 3};
    int parent[] = { -1, 0, 0, 1, 1, 3, 5 };
 
    int n = sizeof(parent) / sizeof(parent[0]);
    cout << "Height is " << findHeight(parent, n);
    return 0;
}

Java




// Java program to find height using parent array
class BinaryTree {
 
    // This function fills depth of i'th element in
    // parent[].  The depth is filled in depth[i].
    void fillDepth(int parent[], int i, int depth[])
    {
 
        // If depth[i] is already filled
        if (depth[i] != 0) {
            return;
        }
 
        // If node at index i is root
        if (parent[i] == -1) {
            depth[i] = 1;
            return;
        }
 
        // If depth of parent is not evaluated before, then
        // evaluate depth of parent first
        if (depth[parent[i]] == 0) {
            fillDepth(parent, parent[i], depth);
        }
 
        // Depth of this node is depth of parent plus 1
        depth[i] = depth[parent[i]] + 1;
    }
 
    // This function returns height of binary tree
    // represented by parent array
    int findHeight(int parent[], int n)
    {
 
        // Create an array to store depth of all nodes/ and
        // initialize depth of every node as 0 (an invalid
        // value). Depth of root is 1
        int depth[] = new int[n];
        for (int i = 0; i < n; i++) {
            depth[i] = 0;
        }
 
        // fill depth of all nodes
        for (int i = 0; i < n; i++) {
            fillDepth(parent, i, depth);
        }
 
        // The height of binary tree is maximum of all
        // depths. Find the maximum value in depth[] and
        // assign it to ht.
        int ht = depth[0];
        for (int i = 1; i < n; i++) {
            if (ht < depth[i]) {
                ht = depth[i];
            }
        }
        return ht;
    }
 
    // Driver program to test above functions
    public static void main(String args[])
    {
 
        BinaryTree tree = new BinaryTree();
 
        // int parent[] = {1, 5, 5, 2, 2, -1, 3};
        int parent[] = new int[] { -1, 0, 0, 1, 1, 3, 5 };
 
        int n = parent.length;
        System.out.println("Height is  "
                           + tree.findHeight(parent, n));
    }
}

Python




# Python program to find height using parent array
 
# This functio fills depth of i'th element in parent[]
# The depth is filled in depth[i]
 
 
def fillDepth(parent, i, depth):
 
    # If depth[i] is already filled
    if depth[i] != 0:
        return
 
    # If node at index i is root
    if parent[i] == -1:
        depth[i] = 1
        return
 
    # If depth of parent is not evaluated before,
    # then evaluate depth of parent first
    if depth[parent[i]] == 0:
        fillDepth(parent, parent[i], depth)
 
    # Depth of this node is depth of parent plus 1
    depth[i] = depth[parent[i]] + 1
 
# This function reutns height of binary tree represented
# by parent array
 
 
def findHeight(parent):
    n = len(parent)
    # Create an array to store depth of all nodes and
    # initialize depth of every node as 0
    # Depth of root is 1
    depth = [0 for i in range(n)]
 
    # fill depth of all nodes
    for i in range(n):
        fillDepth(parent, i, depth)
 
    # The height of binary tree is maximum of all
    # depths. Find the maximum in depth[] and assign
    # it to ht
    ht = depth[0]
    for i in range(1, n):
        ht = max(ht, depth[i])
 
    return ht
 
 
# Driver program to test above function
parent = [-1, 0, 0, 1, 1, 3, 5]
print "Height is %d" % (findHeight(parent))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

C#




using System;
 
// C# program to find height using parent array
public class BinaryTree {
 
    // This function fills depth of i'th element in
    // parent[].  The depth is filled in depth[i].
    public virtual void fillDepth(int[] parent, int i,
                                  int[] depth)
    {
 
        // If depth[i] is already filled
        if (depth[i] != 0) {
            return;
        }
 
        // If node at index i is root
        if (parent[i] == -1) {
            depth[i] = 1;
            return;
        }
 
        // If depth of parent is not evaluated before, then
        // evaluate depth of parent first
        if (depth[parent[i]] == 0) {
            fillDepth(parent, parent[i], depth);
        }
 
        // Depth of this node is depth of parent plus 1
        depth[i] = depth[parent[i]] + 1;
    }
 
    // This function returns height of binary tree
    // represented by parent array
    public virtual int findHeight(int[] parent, int n)
    {
 
        // Create an array to store depth of all nodes/ and
        // initialize depth of every node as 0 (an invalid
        // value). Depth of root is 1
        int[] depth = new int[n];
        for (int i = 0; i < n; i++) {
            depth[i] = 0;
        }
 
        // fill depth of all nodes
        for (int i = 0; i < n; i++) {
            fillDepth(parent, i, depth);
        }
 
        // The height of binary tree is maximum of all
        // depths. Find the maximum value in depth[] and
        // assign it to ht.
        int ht = depth[0];
        for (int i = 1; i < n; i++) {
            if (ht < depth[i]) {
                ht = depth[i];
            }
        }
        return ht;
    }
 
    // Driver program to test above functions
    public static void Main(string[] args)
    {
 
        BinaryTree tree = new BinaryTree();
 
        // int parent[] = {1, 5, 5, 2, 2, -1, 3};
        int[] parent = new int[] { -1, 0, 0, 1, 1, 3, 5 };
 
        int n = parent.Length;
        Console.WriteLine("Height is  "
                          + tree.findHeight(parent, n));
    }
}
 
// This code is contributed by Shrikant13

Javascript




<script>
// javascript program to find height using parent array
 
 
    // This function fills depth of i'th element in parent. The depth is
    // filled in depth[i].
    function fillDepth(parent , i , depth) {
 
        // If depth[i] is already filled
        if (depth[i] != 0) {
            return;
        }
 
        // If node at index i is root
        if (parent[i] == -1) {
            depth[i] = 1;
            return;
        }
 
        // If depth of parent is not evaluated before, then evaluate
        // depth of parent first
        if (depth[parent[i]] == 0) {
            fillDepth(parent, parent[i], depth);
        }
 
        // Depth of this node is depth of parent plus 1
        depth[i] = depth[parent[i]] + 1;
    }
 
    // This function returns height of binary tree represented by
    // parent array
    function findHeight(parent , n) {
 
        // Create an array to store depth of all nodes/ and
        // initialize depth of every node as 0 (an invalid
        // value). Depth of root is 1
        var depth = Array(n).fill(0);
        for (i = 0; i < n; i++) {
            depth[i] = 0;
        }
 
        // fill depth of all nodes
        for (i = 0; i < n; i++) {
            fillDepth(parent, i, depth);
        }
 
        // The height of binary tree is maximum of all depths.
        // Find the maximum value in depth and assign it to ht.
        var ht = depth[0];
        for (i = 1; i < n; i++) {
            if (ht < depth[i]) {
                ht = depth[i];
            }
        }
        return ht;
    }
 
    // Driver program to test above functions
     
 
     
 
        // var parent = [1, 5, 5, 2, 2, -1, 3];
        var parent =[-1, 0, 0, 1, 1, 3, 5 ];
 
        var n = parent.length;
        document.write("Height is  " + findHeight(parent, n));
 
// This code contributed by gauravrajput1
</script>

Javascript




<script>
 
 
 
// javascript program to find height using parent array
 
function fillDepth(parent, index, depth, obj) {
 
    let max = depth;
 
    if (obj[index]) {
        for (let i = 0; i < obj[index].length; i++) {
            max = Math.max(max, fillDepth(parent, obj[index][i], depth + 1, obj))
        }
    }
    return max;
}
 
// This function returns height of binary tree represented by
// parent array
function findHeight(parent, n) {
 
    let root_index;
 
    for (let i = 0; i < n; i++) {
        if (parent[i] === -1) {
            root_index = i;
        }
    }
 
    let obj = {};
 
    for (let i = 0; i < n; i++) {
        if (obj[parent[i]]) {
            let arr = obj[parent[i]];
            arr.push(i)
            obj[parent[i]] = arr;
        }
        else {
            obj[parent[i]] = [i];
        }
    }
 
    return fillDepth(parent, root_index, 1, obj);
}
 
// Driver program to test above functions
 
// var parent = [1, 5, 5, 2, 2, -1, 3];
var parent = [-1, 0, 0, 1, 1, 3, 5];
 
var n = parent.length;
document.write("Height is " + findHeight(parent, n));
 
// This code contributed by gaurav2146
 
 
 
</script>

Output: 

Height is 5

Note that the time complexity of this program seems more than O(n). If we take a closer look, we can observe that the depth of every node is evaluated only once.
This article is contributed by Siddharth. Please write comments if you find anything incorrect or share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :