原题目: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.
给定一个二叉树,求最小深度。最小深度即为根节点至最近叶子节点经过的节点数。经过一番挣扎,最终用两个队列交叉使用来解决,实际上就是一个层次遍历,本机测试还可以,在线编程环境不知道为什么会出错。下边代码中的测试用例为:
import java.util.Queue;
import java.util.LinkedList;
public class HelloWorld {
public static void main(String[] args){
TreeNode root = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
TreeNode node8 = new TreeNode(8);
TreeNode node9 = new TreeNode(9);
root.left = node2;
root.right = node3;
node2.left=node4;
node2.right=node5;
node3.left=node6;
node3.right=node7;
node4.right=node8;
node6.left=node9;
Solution s = new Solution();
System.out.println(s.run(root));
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
static class Solution {
private int minimum = 1;
private Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
private Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
public int run(TreeNode root) {
if (root == null) return 0;
queue1.offer(root);
while(queue1.size()>0 || queue2.size()>0){
if(queue1.size()>0){
while(queue1.size()>0){//此处不能用null来判断,各位一想便知了
TreeNode t = queue1.poll();
if(t.left==null && t.right==null) return minimum;
if(t.left!=null) queue2.offer(t.left);
if(t.right!=null) queue2.offer(t.right);
}
minimum++;
}
if(queue2.size()>0){
while(queue2.size()>0){//此处不能用null来判断,各位一想便知了
TreeNode t = queue2.poll();
if(t.left==null && t.right==null) return minimum;
if(t.left!=null) queue1.offer(t.left);
if(t.right!=null) queue1.offer(t.right);
}
minimum++;
}
}
return -1;
}
}
}
代码输出结果:3
发现有问题可随时指出,谢谢。(第一篇博客,做个爱记笔记的好孩子)