Given a binary tree, find its minimum depth. The minimum depth is the total number of nodes along the shortest path from the root node down to the nearest leaf node.

For example, the minimum depth of the following binary tree is 3. The shortest path is 1 —> 3 —> 6.

Binary Tree – Minimum Depth

Practice this problem

The idea is to traverse the binary tree in a bottom-up manner using postorder traversal and calculate the minimum depth of left and right subtree for each encountered node. The minimum depth of the subtree rooted at any node is one more than the minimum depth of its left and right subtree. If either left or right subtree does not exist for a node, consider the minimum depth returned by the other subtree.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The minimum depth is 3

Java


Download  Run Code

Output:

The minimum depth is 3

Python


Download  Run Code

Output:

The minimum depth is 3

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.

 
The above recursive solution is far from optimal as we might end up traversing the whole tree to find a leaf closest to the root node. The idea is to traverse the tree using BFS instead of DFS. Then the procedure can be terminated upon encountering the first leaf node closest to the root.

The standard algorithm for performing BFS on trees is level order traversal. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The minimum depth is 3

Java


Download  Run Code

Output:

The minimum depth is 3

Python


Download  Run Code

Output:

The minimum depth is 3

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The extra space used by the program is O(n) for the queue data structure.