Given a binary tree, find its minimum depth. The minimum depth is the 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

The idea is to traverse the binary tree in bottom-up manner using post-order 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 equal to the minimum depth of its left and right subtree plus one. 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

Download   Run Code
Output:

The minimum depth is 3

Download   Run Code
Output:

The minimum depth is 3

Download   Run Code
Output:

The minimum depth is 3

The time complexity of the above solution is O(n), and the auxiliary space used 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 on 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

Download   Run Code
Output:

The minimum depth is 3

Download   Run Code
Output:

The minimum depth is 3

Download   Run Code
Output:

The minimum depth is 3

The time complexity of the above solution is O(n), and the extra space used by the program is O(n) for queue data structure.

source