Find Height of Binary Tree represented by Parent array
Last Updated :
23 Jul, 2025
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.
Source: Amazon Interview experience | Set 128 (For SDET)
We strongly recommend minimizing your browser and try this yourself first.
Naive Approach: 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.
Time Complexity: This solution takes O(n2) as we have to search for every node linearly.
Efficient Approach: 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.
- Find the depth of all nodes and fill in an auxiliary array depth[].
- Return maximum value in depth[].
Following are steps to find the depth of a node at index i.
- If it is root, depth[i] is 1.
- If depth of parent[i] is evaluated, depth[i] is depth[parent[i]] + 1.
- 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));
}
}
Python3
# 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 returns 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>
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.
Time Complexity : O(n), where n is the number of nodes in the tree
Auxiliary Space: O(h), where h is the height of the tree.
Iterative Approach(Without creating Binary Tree):
Follow the below steps to solve the given problem
1) We will simply traverse the array from 0 to n-1 using loop.
2) I will initialize a count variable with 0 at each traversal and we will go back and try to reach at -1.
3) Every time when I go back I will increment the count by 1 and finally at reaching -1 we will store the maximum of result and count in result.
4) return result or ans variable.
Below is the implementation of above approach:
C++
// C++ Program to find the height of binary tree
// from parent array without creating the tree and without
// recursion
#include<bits/stdc++.h>
using namespace std;
// function will return the height of given binary
// tree from parent array representation
int findHeight(int arr[], int n){
int ans = 1;
for(int i = 0; i<n; i++){
int count = 1;
int value = arr[i];
while(value != -1){
count++;
value = arr[value];
}
ans = max(ans, count);
}
return ans;
}
// driver program to test above functions
int main(){
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
import java.util.*;
public class Main {
// function will return the height of given binary
// tree from parent array representation
static int findHeight(int arr[], int n) {
int ans = 1;
for(int i = 0; i < n; i++) {
int count = 1;
int value = arr[i];
while(value != -1) {
count++;
value = arr[value];
}
ans = Math.max(ans, count);
}
return ans;
}
// driver program to test above functions
public static void main(String[] args) {
int parent[] = { -1, 0, 0, 1, 1, 3, 5 };
int n = parent.length;
System.out.println("Height is : " + findHeight(parent, n));
}
}
Python3
# Python program to find the height of binary tree
# from parent array without creating the tree and without
# recursion
# function will return the height of given binary
# tree from parent array representation
def findHeight(arr, n):
ans = 1
for i in range(n):
count = 1
value = arr[i]
while(value != -1):
count += 1
value = arr[value]
ans = max(ans, count)
return ans
# driver program to test above function
parent = [-1, 0, 0, 1, 1, 3, 5]
n = len(parent)
print("Height is : ", end="")
print(findHeight(parent, n))
C#
// C# program to find the height of binary tree
// from parent array without creating the tree and without
// recursion
using System;
public class Program
{
// function will return the height of given binary
// tree from parent array representation
static int FindHeight(int[] arr, int n)
{
int ans = 1;
for (int i = 0; i < n; i++)
{
int count = 1;
int value = arr[i];
while (value != -1)
{
count++;
value = arr[value];
}
ans = Math.Max(ans, count);
}
return ans;
}
// driver program to test above functions
public static void Main()
{
int[] parent = { -1, 0, 0, 1, 1, 3, 5 };
int n = parent.Length;
Console.WriteLine("Height is : " + FindHeight(parent, n));
}
}
JavaScript
// JavaScript Program to find the height of binary tree
// from parent array without creating the tree and without
// recursion
// function will return the height of given binary
// tree from parent array representation
function findHeight(arr, n){
let ans = 1;
for(let i = 0; i<n; i++){
let count = 1;
let value = arr[i];
while(value != -1){
count++;
value = arr[value];
}
ans = Math.max(ans, count);
}
return ans;
}
// driver program to test above function
let parent = [ -1, 0, 0, 1, 1, 3, 5 ];
let n = parent.length;
console.log("Height is : " + findHeight(parent, n));
Time Complexity: O(N^2)
Auxiliary Space: O(1), constant space.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem