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.
Output: 2 Explanation: Minimum depth is between nodes 1 and 2 since minimum depth is defined as the number of nodes along the shortest path from the root node down to the nearest leaf node.
The idea is to traverse the binary tree level by level using a queue. We start from the root node and process all nodes at the current level before moving to the next. A variable depth keeps track of the current level. As soon as we encounter the first leaf node, we return the current depth, because BFS guarantees that this is the minimum depth of the tree.
We begin with root and add it to the queue and initialize depth as 1.
At every level, we remove current level nodes (using queue size) and push nodes of next level.
We increment depth after every level
Whenever we encounter a leaf node, we return depth.