Find Height of Binary Tree represented by Parent array | This function fills depth of i 'th element in parent. The depth is  filled in depth[i]. ; If depth [ i ] is already filled ; If node at index i is root ; If depth of parent is not evaluated before , then evaluate depth of parent first ; Depth of this node is depth of parent plus 1 ; This function returns height of binary tree represented by parent array ; 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 ; fill depth of all nodes ; The height of binary tree is maximum of all depths . Find the maximum value in depth and assign it to ht . ; var parent = [ 1 , 5 , 5 , 2 , 2 , - 1 , 3 ] ;
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 ( " " + findHeight ( parent , n ) ) ;