You are given an array of length N. The array stores information about an n-ary tree. And the n-ary tree has N-nodes numbered 0 – (N-1).The **i**th index in the array contains the parent nodes number **j**. Given this array find the height of the tree. The parent of the root is -1

It would be good to solve this problem in O(n).

### Like this:

Like Loading...

*Related*

Guru

April 6, 2010 at 6:14 am

Logic: Traverse the Array from the last.

The last element in the array will be the leaf of the highest sub-tree.

1. Initialize a variable lets say height =0;

2. Read the last element, it has the its parent value, lets say val.

3. array[val] will give the parent to parent of the last node. Increment the variable.

4. Do the same till you find the root -1;

5. The value of the height is the height of the tree.

ranganathg

April 7, 2010 at 6:36 pm

Why is the last element in the array the leaf of the heighest sub tree?

chiku

November 16, 2010 at 5:49 am

@ranganath: I have O(n) time and O(n) space solution to this one. If there is a solution which uses constant space lemme know the existence of it (not the algorithm!).

chiku

November 16, 2010 at 6:09 am

@ranganath: actually I can do in O(n) time and O(1) space if I’m allowed to destroy array!

ranganathg

November 16, 2010 at 10:18 am

@chiku,

if you can share your solution, that would be great. My solution took O(n) time/extra space. This was my interview question at Trilogy.