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.
这个题跟求最大深度差不多。
使用递归最简单。不使用递归就是在层序遍历的时候判断。。见代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
/* if(root.left==null&&root.right==null) return 1;
if(root.left==null) return minDepth(root.right)+1;
if(root.right==null) return minDepth(root.left)+1;
int left=minDepth(root.left);
int right=minDepth(root.right);
return Math.min(left,right)+1;
*/
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
int count=1;
while(!q.isEmpty()){
int size=q.size();
for(int i=0;i<size;i++){
TreeNode node=q.poll();
if(node.left==null&&node.right==null) return count;
if(node.left!=null) q.add(node.left);
if(node.right!=null) q.add(node.right);
}
count++;
}
return count;
}
}