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++
#include <bits/stdc++.h>
using namespace std;
void fillDepth( int parent[], int i, int depth[])
{
if (depth[i])
return ;
if (parent[i] == -1) {
depth[i] = 1;
return ;
}
if (depth[parent[i]] == 0)
fillDepth(parent, parent[i], depth);
depth[i] = depth[parent[i]] + 1;
}
int findHeight( int parent[], int n)
{
int depth[n];
for ( int i = 0; i < n; i++)
depth[i] = 0;
for ( int i = 0; i < n; i++)
fillDepth(parent, i, depth);
int ht = depth[0];
for ( int i = 1; i < n; i++)
if (ht < depth[i])
ht = depth[i];
return ht;
}
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
class BinaryTree {
void fillDepth( int parent[], int i, int depth[])
{
if (depth[i] != 0 ) {
return ;
}
if (parent[i] == - 1 ) {
depth[i] = 1 ;
return ;
}
if (depth[parent[i]] == 0 ) {
fillDepth(parent, parent[i], depth);
}
depth[i] = depth[parent[i]] + 1 ;
}
int findHeight( int parent[], int n)
{
int depth[] = new int [n];
for ( int i = 0 ; i < n; i++) {
depth[i] = 0 ;
}
for ( int i = 0 ; i < n; i++) {
fillDepth(parent, i, depth);
}
int ht = depth[ 0 ];
for ( int i = 1 ; i < n; i++) {
if (ht < depth[i]) {
ht = depth[i];
}
}
return ht;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
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
def fillDepth(parent, i, depth):
if depth[i] ! = 0 :
return
if parent[i] = = - 1 :
depth[i] = 1
return
if depth[parent[i]] = = 0 :
fillDepth(parent, parent[i], depth)
depth[i] = depth[parent[i]] + 1
def findHeight(parent):
n = len (parent)
depth = [ 0 for i in range (n)]
for i in range (n):
fillDepth(parent, i, depth)
ht = depth[ 0 ]
for i in range ( 1 , n):
ht = max (ht, depth[i])
return ht
parent = [ - 1 , 0 , 0 , 1 , 1 , 3 , 5 ]
print ( "Height is %d" % (findHeight(parent)))
|
C#
using System;
public class BinaryTree {
public virtual void fillDepth( int [] parent, int i,
int [] depth)
{
if (depth[i] != 0) {
return ;
}
if (parent[i] == -1) {
depth[i] = 1;
return ;
}
if (depth[parent[i]] == 0) {
fillDepth(parent, parent[i], depth);
}
depth[i] = depth[parent[i]] + 1;
}
public virtual int findHeight( int [] parent, int n)
{
int [] depth = new int [n];
for ( int i = 0; i < n; i++) {
depth[i] = 0;
}
for ( int i = 0; i < n; i++) {
fillDepth(parent, i, depth);
}
int ht = depth[0];
for ( int i = 1; i < n; i++) {
if (ht < depth[i]) {
ht = depth[i];
}
}
return ht;
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
int [] parent = new int [] { -1, 0, 0, 1, 1, 3, 5 };
int n = parent.Length;
Console.WriteLine( "Height is "
+ tree.findHeight(parent, n));
}
}
|
Javascript
<script>
function fillDepth(parent , i , depth) {
if (depth[i] != 0) {
return ;
}
if (parent[i] == -1) {
depth[i] = 1;
return ;
}
if (depth[parent[i]] == 0) {
fillDepth(parent, parent[i], depth);
}
depth[i] = depth[parent[i]] + 1;
}
function findHeight(parent , n) {
var depth = Array(n).fill(0);
for (i = 0; i < n; i++) {
depth[i] = 0;
}
for (i = 0; i < n; i++) {
fillDepth(parent, i, depth);
}
var ht = depth[0];
for (i = 1; i < n; i++) {
if (ht < depth[i]) {
ht = depth[i];
}
}
return ht;
}
var parent =[-1, 0, 0, 1, 1, 3, 5 ];
var n = parent.length;
document.write( "Height is " + findHeight(parent, n));
</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++
#include<bits/stdc++.h>
using namespace std;
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;
}
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 {
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;
}
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
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
parent = [ - 1 , 0 , 0 , 1 , 1 , 3 , 5 ]
n = len (parent)
print ( "Height is : " , end = "")
print (findHeight(parent, n))
|
C#
using System;
public class Program
{
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;
}
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
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;
}
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.