Let v be a node of a tree T. The depth of a node v can defined as follows:
- If v is the root, then the depth of v is 1.
- Otherwise, the depth of v is 1 plus the depth of the parent of v.
Based on the above definition, the recursive algorithm depth, shown in the below Algorithm, computes the depth of a node v of Tree by calling itself recursively on the parent of v, and adding 1 to the value returned.
Algorithm depth(T, y):
- Step 1: If
T.isRoot(v), then return1 - Step 2: Else, return
1 + depth(T, T. parent(v))
The height of a tree T is equal to the maximum depth of an external node of T. While this definition is correct, it does not lead to an efficient algorithm. Indeed, if we were to apply the above depth-finding algorithm to each node in the tree T, we would derive an O(n2)-time algorithm to compute the height of T.
According to above statement how can it be O(n2)? If we try this algorithm on every external node, then it takes O(n), and to find maximum it will O(n). So the total complexity should be O(n)+O(n) = O(2n)==O(n), right?

