Find Height of Binary Tree represented by Parent array
Last Updated : 13 Jul, 2026
Given a parent array arr[] representing a binary tree, where arr[i] denotes the parent of node i, return the height of the tree. The root is the unique node whose parent is -1.
Note: The height of a tree is the number of nodes on the longest path from the root to a leaf.
Examples:
Input: arr[] = [-1, 0, 0, 1, 1, 3, 5] Output: 5 Explanation: The longest path from the root node 0 to a leaf is 0 -> 1 -> 3 -> 5 -> 6, which contains 5 nodes. Therefore, the height of the tree is 5.
Input: arr[] = [-1, 0, 0] Output: 2 Explanation: The longest root-to-leaf path is either 0 -> 1 or 0 -> 2, each containing 2 nodes. Therefore, the height of the tree is 2.
[Naive Approach] Brute Force Approach - O(n^2) Time and O(1) Space
The idea is to determine the depth of every node by repeatedly moving to its parent until the root is reached. Since the height of a tree is the maximum depth among all its nodes, we compute the depth of each node and return the largest one.
Initialize a variable height to store the maximum depth of the tree.
Traverse each node in the parent array.
For every node, repeatedly move to its parent until the root (-1) is reached, counting the number of nodes visited as its depth.
Compare the current node's depth with height and update height if it is larger.
Repeat this process for all nodes in the array.
Return the maximum depth obtained as the height of the tree.
C++
#include<algorithm>#include<iostream>#include<vector>usingnamespacestd;// Returns the height of the binary tree represented by the parent array.intfindHeight(vector<int>&arr){intn=arr.size();// Stores the maximum depth found so far.intheight=0;// Traverse every node in the tree.for(inti=0;i<n;i++){intdepth=0;intnode=i;// Move upwards through the parent chain until the root is reached.while(node!=-1){depth++;node=arr[node];}// Update the maximum depth encountered.height=max(height,depth);}returnheight;}intmain(){// Parent array representation of the binary tree.// Index : 0 1 2 3 4 5 6// Parent : -1 0 0 1 1 3 5vector<int>arr={-1,0,0,1,1,3,5};cout<<findHeight(arr)<<endl;return0;}
Java
importjava.util.*;publicclassGFG{// Returns the height of the binary tree represented by// the parent array.staticintfindHeight(int[]arr){intn=arr.length;// Stores the maximum depth found so far.intheight=0;// Traverse every node in the tree.for(inti=0;i<n;i++){intdepth=0;intnode=i;// Move upwards through the parent chain until// the root is reached.while(node!=-1){depth++;node=arr[node];}// Update the maximum depth encountered.height=Math.max(height,depth);}returnheight;}publicstaticvoidmain(String[]args){// Parent array representation of the binary tree.// Index : 0 1 2 3 4 5 6// Parent : -1 0 0 1 1 3 5int[]arr={-1,0,0,1,1,3,5};System.out.println(findHeight(arr));}}
Python
# Returns the height of the binary tree represented by the parent array.deffindHeight(arr):n=len(arr)# Stores the maximum depth found so far.height=0# Traverse every node in the tree.foriinrange(n):depth=0node=i# Move upwards through the parent chain until the root is reached.whilenode!=-1:depth+=1node=arr[node]# Update the maximum depth encountered.height=max(height,depth)returnheight# Driver Codeif__name__=="__main__":# Parent array representation of the binary tree.# Index : 0 1 2 3 4 5 6# Parent : -1 0 0 1 1 3 5arr=[-1,0,0,1,1,3,5]print(findHeight(arr))
C#
usingSystem;classGFG{// Returns the height of the binary tree represented by// the parent array.staticintfindHeight(int[]arr){intn=arr.Length;// Stores the maximum depth found so far.intheight=0;// Traverse every node in the tree.for(inti=0;i<n;i++){intdepth=0;intnode=i;// Move upwards through the parent chain until// the root is reached.while(node!=-1){depth++;node=arr[node];}// Update the maximum depth encountered.height=Math.Max(height,depth);}returnheight;}staticvoidMain(){// Parent array representation of the binary tree.// Index : 0 1 2 3 4 5 6// Parent : -1 0 0 1 1 3 5int[]arr={-1,0,0,1,1,3,5};Console.WriteLine(findHeight(arr));}}
JavaScript
// Returns the height of the binary tree represented by the// parent array.functionfindHeight(arr){constn=arr.length;// Stores the maximum depth found so far.letheight=0;// Traverse every node in the tree.for(leti=0;i<n;i++){letdepth=0;letnode=i;// Move upwards through the parent chain until the// root is reached.while(node!==-1){depth++;node=arr[node];}// Update the maximum depth encountered.height=Math.max(height,depth);}returnheight;}// Driver Code// Parent array representation of the binary tree.// Index : 0 1 2 3 4 5 6// Parent : -1 0 0 1 1 3 5constarr=[-1,0,0,1,1,3,5];console.log(findHeight(arr));
Output
5
[Better Approach] By Constructing tree and Level Order Traversal - O(n) Time and O(n) Space
The idea is to reconstruct the binary tree using parent array because parent array stores parent-child relationships. Once the tree is built, we perform a level order traversal (BFS), where each level corresponds to one level of the tree, and the total number of levels gives its height.
Create a tree node for every index in the parent array.
Traverse the parent array and connect each node to its parent as either the left or right child, while identifying the root node.
Initialize a queue and insert the root into it.
Perform a level order traversal by processing all nodes at the current level before moving to the next.
After processing each level, increment the height by one.
Continue until the queue becomes empty and return the computed height.
C++
#include<iostream>#include<queue>#include<vector>usingnamespacestd;classNode{public:intval;Node*left,*right;Node(intx){val=x;left=right=nullptr;}};// Returns the height of the binary tree represented by the parent array.intfindHeight(vector<int>&arr){intn=arr.size();if(n==0)return0;// Create a tree node for every index.vector<Node*>nodes(n);for(inti=0;i<n;i++)nodes[i]=newNode(i);Node*root=nullptr;// Build the binary tree from the parent array.for(inti=0;i<n;i++){if(arr[i]==-1){root=nodes[i];}else{// Attach the node as the left child if vacant,// otherwise as the right child.if(nodes[arr[i]]->left==nullptr)nodes[arr[i]]->left=nodes[i];elsenodes[arr[i]]->right=nodes[i];}}// Perform level order traversal to calculate the height.queue<Node*>q;q.push(root);intheight=0;while(!q.empty()){intsize=q.size();while(size--){Node*curr=q.front();q.pop();if(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}// One complete level has been processed.height++;}returnheight;}intmain(){// Parent array representation of the binary tree.vector<int>arr={-1,0,0,1,1,3,5};cout<<findHeight(arr);return0;}
Java
importjava.util.*;classNode{intval;Nodeleft,right;Node(intx){val=x;}}publicclassGFG{// Returns the height of the binary tree represented by// the parent array.staticintfindHeight(int[]arr){intn=arr.length;if(n==0)return0;// Create a tree node for every index.Node[]nodes=newNode[n];for(inti=0;i<n;i++)nodes[i]=newNode(i);Noderoot=null;// Build the binary tree from the parent array.for(inti=0;i<n;i++){if(arr[i]==-1){root=nodes[i];}else{// Attach the node as the left child if// vacant, otherwise as the right child.if(nodes[arr[i]].left==null)nodes[arr[i]].left=nodes[i];elsenodes[arr[i]].right=nodes[i];}}// Perform level order traversal to calculate the// height.Queue<Node>q=newLinkedList<>();q.offer(root);intheight=0;while(!q.isEmpty()){intsize=q.size();while(size-->0){Nodecurr=q.poll();if(curr.left!=null)q.offer(curr.left);if(curr.right!=null)q.offer(curr.right);}// One complete level has been processed.height++;}returnheight;}publicstaticvoidmain(String[]args){// Parent array representation of the binary tree.int[]arr={-1,0,0,1,1,3,5};System.out.println(findHeight(arr));}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.val=xself.left=Noneself.right=None# Returns the height of the binary tree represented by the parent array.deffindHeight(arr):n=len(arr)ifn==0:return0# Create a tree node for every index.nodes=[Node(i)foriinrange(n)]root=None# Build the binary tree from the parent array.foriinrange(n):ifarr[i]==-1:root=nodes[i]else:# Attach the node as the left child if vacant,# otherwise as the right child.ifnodes[arr[i]].leftisNone:nodes[arr[i]].left=nodes[i]else:nodes[arr[i]].right=nodes[i]# Perform level order traversal to calculate the height.q=deque([root])height=0whileq:size=len(q)whilesize:curr=q.popleft()ifcurr.left:q.append(curr.left)ifcurr.right:q.append(curr.right)size-=1# One complete level has been processed.height+=1returnheight# Driver Codeif__name__=="__main__":# Parent array representation of the binary tree.arr=[-1,0,0,1,1,3,5]print(findHeight(arr))
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintval;publicNodeleft,right;publicNode(intx){val=x;}}classGFG{// Returns the height of the binary tree represented by// the parent array.staticintfindHeight(int[]arr){intn=arr.Length;if(n==0)return0;// Create a tree node for every index.Node[]nodes=newNode[n];for(inti=0;i<n;i++)nodes[i]=newNode(i);Noderoot=null;// Build the binary tree from the parent array.for(inti=0;i<n;i++){if(arr[i]==-1){root=nodes[i];}else{// Attach the node as the left child if// vacant, otherwise as the right child.if(nodes[arr[i]].left==null)nodes[arr[i]].left=nodes[i];elsenodes[arr[i]].right=nodes[i];}}// Perform level order traversal to calculate the// height.Queue<Node>q=newQueue<Node>();q.Enqueue(root);intheight=0;while(q.Count>0){intsize=q.Count;while(size-->0){Nodecurr=q.Dequeue();if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}// One complete level has been processed.height++;}returnheight;}staticvoidMain(){// Parent array representation of the binary tree.int[]arr={-1,0,0,1,1,3,5};Console.WriteLine(findHeight(arr));}}
JavaScript
classNode{constructor(val){this.val=val;this.left=null;this.right=null;}}// Returns the height of the binary tree represented by the// parent array.functionfindHeight(arr){constn=arr.length;if(n===0)return0;// Create a tree node for every index.constnodes=[];for(leti=0;i<n;i++)nodes.push(newNode(i));letroot=null;// Build the binary tree from the parent array.for(leti=0;i<n;i++){if(arr[i]===-1){root=nodes[i];}else{// Attach the node as the left child if vacant,// otherwise as the right child.if(nodes[arr[i]].left===null)nodes[arr[i]].left=nodes[i];elsenodes[arr[i]].right=nodes[i];}}// Perform level order traversal to calculate the// height.constq=[root];letheight=0;while(q.length>0){letsize=q.length;while(size--){constcurr=q.shift();if(curr.left)q.push(curr.left);if(curr.right)q.push(curr.right);}// One complete level has been processed.height++;}returnheight;}// Driver Code// Parent array representation of the binary tree.constarr=[-1,0,0,1,1,3,5];console.log(findHeight(arr));
Output
5
[Expected Approach] Using Dynamic Programming - O(n) Time and O(n) Space
Instead of constructing the binary tree, we directly use the parent array to compute the depth of each node. While moving towards the root, if we encounter a node whose depth is already known, we reuse it and assign depths to all visited nodes, ensuring each node's depth is computed only once.
Create a height array initialized with 0 to store the depth of each node.
Traverse every node in the parent array.
From the current node, move towards the root until reaching either the root or a node whose depth has already been computed.
Use the known depth (if available) to determine the depth of the current node.
Traverse the same path again and assign depths to all previously unvisited nodes while moving upward.
Keep updating the maximum depth encountered and return it as the height of the tree.
C++
#include<algorithm>#include<iostream>#include<vector>usingnamespacestd;// Returns the height of the binary tree represented by the parent array.intfindHeight(vector<int>&arr){intn=arr.size();// Stores the depth of each node.vector<int>height(n,0);intres=0;// Traverse every node.for(inti=0;i<n;i++){intnode=i;intcnt=0;// Move upwards until reaching the root// or a node whose depth is already known.while(node!=-1&&height[node]==0){cnt++;node=arr[node];}// Reuse the already computed depth.if(node!=-1)cnt+=height[node];node=i;// Assign depths to all unvisited nodes on this path.while(node!=-1&&height[node]==0){height[node]=cnt;cnt--;node=arr[node];}// Update the maximum depth.res=max(res,height[i]);}returnres;}intmain(){// Parent array representation of the binary tree.vector<int>arr={-1,0,0,1,1,3,5};cout<<findHeight(arr);return0;}
Java
importjava.util.*;publicclassGFG{// Returns the height of the binary tree represented by// the parent array.staticintfindHeight(int[]arr){intn=arr.length;// Stores the depth of each node.int[]height=newint[n];intres=0;// Traverse every node.for(inti=0;i<n;i++){intnode=i;intcnt=0;// Move upwards until reaching the root// or a node whose depth is already known.while(node!=-1&&height[node]==0){cnt++;node=arr[node];}// Reuse the already computed depth.if(node!=-1)cnt+=height[node];node=i;// Assign depths to all unvisited nodes on this// path.while(node!=-1&&height[node]==0){height[node]=cnt;cnt--;node=arr[node];}// Update the maximum depth.res=Math.max(res,height[i]);}returnres;}publicstaticvoidmain(String[]args){// Parent array representation of the binary tree.int[]arr={-1,0,0,1,1,3,5};System.out.println(findHeight(arr));}}
Python
# Returns the height of the binary tree represented by the parent array.deffindHeight(arr):n=len(arr)# Stores the depth of each node.height=[0]*nres=0# Traverse every node.foriinrange(n):node=icnt=0# Move upwards until reaching the root# or a node whose depth is already known.whilenode!=-1andheight[node]==0:cnt+=1node=arr[node]# Reuse the already computed depth.ifnode!=-1:cnt+=height[node]node=i# Assign depths to all unvisited nodes on this path.whilenode!=-1andheight[node]==0:height[node]=cntcnt-=1node=arr[node]# Update the maximum depth.res=max(res,height[i])returnres# Driver Codeif__name__=="__main__":# Parent array representation of the binary tree.arr=[-1,0,0,1,1,3,5]print(findHeight(arr))
C#
usingSystem;classGFG{// Returns the height of the binary tree represented by// the parent array.staticintfindHeight(int[]arr){intn=arr.Length;// Stores the depth of each node.int[]height=newint[n];intres=0;// Traverse every node.for(inti=0;i<n;i++){intnode=i;intcnt=0;// Move upwards until reaching the root// or a node whose depth is already known.while(node!=-1&&height[node]==0){cnt++;node=arr[node];}// Reuse the already computed depth.if(node!=-1)cnt+=height[node];node=i;// Assign depths to all unvisited nodes on this// path.while(node!=-1&&height[node]==0){height[node]=cnt;cnt--;node=arr[node];}// Update the maximum depth.res=Math.Max(res,height[i]);}returnres;}staticvoidMain(){// Parent array representation of the binary tree.int[]arr={-1,0,0,1,1,3,5};Console.WriteLine(findHeight(arr));}}
JavaScript
// Returns the height of the binary tree represented by the// parent array.functionfindHeight(arr){constn=arr.length;// Stores the depth of each node.constheight=newArray(n).fill(0);letres=0;// Traverse every node.for(leti=0;i<n;i++){letnode=i;letcnt=0;// Move upwards until reaching the root// or a node whose depth is already known.while(node!==-1&&height[node]===0){cnt++;node=arr[node];}// Reuse the already computed depth.if(node!==-1)cnt+=height[node];node=i;// Assign depths to all unvisited nodes on this// path.while(node!==-1&&height[node]===0){height[node]=cnt;cnt--;node=arr[node];}// Update the maximum depth.res=Math.max(res,height[i]);}returnres;}// Driver Code// Parent array representation of the binary tree.constarr=[-1,0,0,1,1,3,5];console.log(findHeight(arr));