How to find the minimum depth of a binary tree

The minimum depth of a binary tree is the number of nodes from the root node to the nearest leaf node.

Consider the binary tree below:

svg viewer

The minimum depth of this tree is 33; it is comprised of nodes 1, 2, and 4.

Let’s look at solutions to calculate the minimum depth of a given binary tree.

1. Recursive solution

The idea is to check if every node is a leaf node. If the current node is a leaf node, return 11. Otherwise, if the node has no left sub-tree, then recur on the right sub-tree. Similarly, if the node has no right sub-tree, then recur on the left sub-tree. Finally, if a node has both left and right sub-trees, recur on both and return the minimum value.

Implementation

Using the binary tree illustrated above, the algorithm is implemented as follows:

2. Level order traversal solution

Since all the nodes are traversed in the recursive solution described above, it has a time complexity of O(n)O(n). However, note​ that even if the minimum depth is found immediately after the root node, the rest of the binary tree is still traversed.

The algorithm can be optimized further using the idea behind level-order traversal. Before reading ahead, spend some time thinking​ about how a level-order traversal can be used to optimize the minimum depth’s calculation.

In the binary tree illustrated earlier, the algorithm would stop once we reached node 4, so there would be no need to traverse nodes 5, 6,7, and 8.

Implementation

Copyright ©2024 Educative, Inc. All rights reserved