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:
The minimum depth of this tree is ; it is comprised of nodes 1, 2, and 4.
Let’s look at solutions to calculate the minimum depth of a given binary tree.
The idea is to check if every node is a leaf node. If the current node is a leaf node, return . 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.
Using the binary tree illustrated above, the algorithm is implemented as follows:
Since all the nodes are traversed in the recursive solution described above, it has a time complexity of . 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.