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.
Solution 1 DFS
1ms 12.55
public class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
return getMin(root);
}
public int getMin(TreeNode root){
if(root == null){
return Integer.MAX_VALUE;
}
if(root.left == null && root.right == null){
return 1;
}
return Math.min(getMin(root.left), getMin(root.right)) + 1;
}
}
Solution 2 BFS
public class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
int depth = 1;
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
for(int i = 0; i < size; i++){
TreeNode temp = q.poll();
if(temp.left != null){
q.offer(temp.left);
}
if(temp.right != null){
q.offer(temp.right);
}
if(temp.left == null && temp.right == null){
return depth;
}
}
depth++;
}
return depth;
}
}