Question: 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.
Note: A leaf is a node with no children. LinkToQuestion
#Solution This question looks similar to other tree questions, I will be using BFS because it's concerned with the shortest path in a tree. Meaning we don't have to transverse the entire tree before we can get a Leaf node.
The first thing to do is to check if the root is null and if it is we just return zero because it doesn't have depth. But if the root is not null, we need to create a Queue to store the value of the node as we traverse the tree. Now we are using a queue so that we can make use of the FIFO operation while transversing a tree, and then we create an integer variable that we will use to store the minimum depth and set it to 1 as the initial value. We then loop over the Queue at long as the queue is not empty using a While loop. In the while loop, we create another condition that checks if the Node that was polled from the queue is a leaf node. If it is we just return the result variable but if it is not we then push the value of the left and right into the queue as long as they aren't null; We continue the operation until we get a leaf node.
class Solution {
public int minDepth(TreeNode root) {
if(root == null)return 0;
int result = 1;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
while(size -- > 0){
TreeNode node = q.poll();
if(node.left ==null && node.right == null)return result;
if(node.left !=null)q.offer(node.left);
if(node.right !=null)q.offer(node.right);
}
result++;
}
return result;
}
}
#personalJournal
#LearningByExplaining