Find Height of Binary Tree represented by Parent array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n that denotes a tree. Our task is to find height of Binary Tree represented by Parent array. 

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties −

  • The value of the key of the left sub-tree is less than the value of its parent (root) node's key.
  • The value of the key of the right subtree is greater than or equal to the value of its parent (root) node's key.

Height of a tree is the number of nodes traversed when going from root node to the farthest leaf node.

Solution Approach: 

A simple solution to the problem is by creating a tree from the parent array. Finding the root of this tree and recurring for the found index making left and right subtree and then returns the maximum height.

A more efficient method would be calculating the depth of nodes from the array and store then store it in depth array. From this array return the maximum depth.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

void findAllDepths(int arr[], int i, int nodeDepth[]) {
   
   if (nodeDepth[i])
      return;
   if (arr[i] == -1) {
     
      nodeDepth[i] = 1;
      return;
   }
   if (nodeDepth[arr[i]] == 0)
      findAllDepths(arr, arr[i], nodeDepth);
   nodeDepth[i] = nodeDepth[arr[i]] + 1;
}

int findMaxHeightBT(int arr[], int n) {

   int nodeDepth[n];
   for (int i = 0; i < n; i++)
      nodeDepth[i] = 0;
   for (int i = 0; i < n; i++)
      findAllDepths(arr, i, nodeDepth);
   int maxHeight = nodeDepth[0];
   for (int i=1; i<n; i++)
      if (maxHeight < nodeDepth[i])
         maxHeight = nodeDepth[i];
   return maxHeight;
}

int main() {
   
   int arr[] = {-1, 0, 0, 1, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"The maximum height of binary Tree is "<<findMaxHeightBT(arr, n);
   return 0;
}

Output −

The maximum height of binary Tree is 3
raja
Published on 22-Jan-2021 13:46:31
Advertisements