1. Introduction

A tree’s height and depth are important attributes to consider in complexity analysis as well as for numerous algorithms. In this tutorial, we’ll try to show the difference between these two attributes.

2. Problem Explanation

For each node in a tree, we can define two features: height and depth. A node’s height is the number of edges to its most distant leaf node. On the other hand, a node’s depth is the number of edges back up to the root. So, the root always has a depth of 0 while leaf nodes always have a height of 0. And if we look at the tree as a whole, its depth and height are both the root height.

Height vs. Depth

3. Flowchart

Calculating the height or depth for any node can be done using breadth-first search (BFS). But, we’re going to leave the general case for a future post. Simply put, we can find the height recursively by setting the height of the node as the maximum height of its children + 1 :

Find Node Height

For depth, if we assume that each node in the tree stores its parent node, we can traverse from our target node up to the root, counting the edges along the way:

Find Node Depth

4. Pseudocode

Let’s see these two now side-by-side. As stated earlier, with height, we traverse downwards and depth, upwards:

Rendered by QuickLaTeX.com

Rendered by QuickLaTeX.com

5. Complexity

We can also compare their complexities. Since we used BFS for finding the height, the complexity is O(n) where n is the number of nodes in the tree. As for the depth algorithm, we iterate over the edges from the target node up to the root. Thus, we can easily see that the time complexity for finding the depth of a node is O(log\;n), and the worst case will be O(n). Also, the space complexity is O(n) for finding height and depth. In the case of finding the height, we need to allocate memory for the BFS queue (which is allocated automatically in the recursive solution). And we need to allocate space for the parents in the case of finding the depth.

6. Conclusion

In this short article, we showed the difference between tree height and depth. To do this, we examined approaches for calculating them and compared their space-time complexities.

guest
0 Comments
Inline Feedbacks
View all comments