class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int high =1;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode cur = queue.poll();
if(cur.left==null && cur.right==null)
return high;
if(cur.left!=null)
queue.add(cur.left);
if(cur.right!=null)
queue.add(cur.right);
}
high++;
}
return 0;
}
}
就是一个简单的BFS算法。
属于基础题。
详细题解在此BFS详解。