![]() |
VOOZH | about |
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.
The height of a Binary Tree is the number of nodes on the path from the root to the deepest leaf node, and 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
Source: Amazon Interview experience | Set 128 (For SDET)
We strongly recommend minimizing your browser and try this yourself first.
Naive Approach: A simple solution is to first construct the tree and then find the height of the constructed binary tree. The tree can be constructed recursively by first searching the current root, then recurring for the found indexes and making them left and right subtrees of the root.
Time Complexity: This solution takes O(n2) as we have to search for every node linearly.
Efficient Approach: An efficient solution can solve the above problem in O(n) time. The idea is to first calculate the depth of every node and store it in an array depth[]. Once we have the depths of all nodes, we return the maximum of all depths.
Following are steps to find the depth of a node at index i.
Following is the implementation of the above idea.
Height is 5
Note that the time complexity of this program seems more than O(n). If we take a closer look, we can observe that the depth of every node is evaluated only once.
Time Complexity : O(n), where n is the number of nodes in the tree
Auxiliary Space: O(h), where h is the height of the tree.
Iterative Approach(Without creating Binary Tree):
Follow the below steps to solve the given problem
1) We will simply traverse the array from 0 to n-1 using loop.
2) I will initialize a count variable with 0 at each traversal and we will go back and try to reach at -1.
3) Every time when I go back I will increment the count by 1 and finally at reaching -1 we will store the maximum of result and count in result.
4) return result or ans variable.
Below is the implementation of above approach:
Height is : 5
Time Complexity: O(N^2)
Auxiliary Space: O(1), constant space.