Find Height of Binary Tree represented by Parent array

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. Height of a Binary Tree is number of nodes on the path from root to the deepest leaf node, 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
class Solution {
    public int solve(int[] arr) {
        int[] depth = new int[arr.length];
        int max = 0;
        for (int i = 0; i < arr.length; i++) {
            depth[i] = fillDepth(arr, depth, i);
            max = Math.max(max, depth[i]);
        }
        return max;
    }

    public int fillDepth(int[] arr, int[] depth, int index) {
        if (arr[index] == -1)
            depth[index] = 0;
        else if (depth[index] == 0)
            depth[index] = 1 + fillDepth(arr, depth, arr[index]);
        return depth[index];
    }
}

Last updated