题目描述:
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.
读题:
找出二叉树的最短深度。用广度优先搜索。
知识储备:
广度优先搜索树
1. 从根节点开始,搜索他的子节点;
2. 搜索所有处在第二层子节点他们的子节点;
3. 以此类推;
4. 直到某个节点不存在子节点,则该节点到根节点的路径为最短路径。
Queue队列:
主要用到的函数
add | 增加一个元素 | 如果队列已满,则抛出一个IIIegaISlabEepeplian异常 |
remove | 移除并返回队列头部的元素 | 如果队列为空,则抛出一个NoSuchElementException异常 |
peek | 返回队列头部的元素 | 如果队列为空,则返回null |
size | 返回队列的大小 | 如果队列为空,则返回0 |
解题思路:
1. 用队列来存储每一层的节点;
2. 从根节点开始,把每一层的节点放入队列,记录队列大小,即该层的节点数;
2. 当循环次数小于该层节点数,从队列的头部开始,如果该节点有子节点,则将他的子节点放进队列尾部,然后移除该节点;
3. 以此类推;
4. 直到某个节点不存在子节点,则结束。
提交代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
int depth = 1;
queue.add(root);
TreeNode head = root;
while (true) {
int size = queue.size();
for (int i = 0; i < size; i++) {
if (head.left == null && head.right == null) {
return depth;
} else {
if (head.left != null) {
queue.add(head.left);
}
if (head.right != null) {
queue.add(head.right);
}
queue.remove();
head = queue.peek();
}
}
depth++;
}
}
}