题目: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.
//递归
public class Solution {
public int run(TreeNode root){
if (root == null){
return 0;
}
if(root.left == null||root.right == null){
return run(root.right)+run(root.left)+1;
}
if(root.left != null&&root.right != null){
return Math.min(run(root.right),run(root.left))+1;
}
return 0;
}
}
//非递归
public int run(TreeNode root){
if(root == null){
return 0;
}
int level = 0;
TreeNode p,last = root;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
p = queue.poll();
if(p.right ==null&&p.left == null){
level++;
break;
}
if(p.right !=null){
queue.offer(p.right);
}
if(p.left != null){
queue.offer(p.left);
}
if(last == p){
level++;
last = queue.peekLast();
}
}
return level;
}