给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
提示:
- 树中节点数的范围在
[0, 105]内 -1000 <= Node.val <= 1000
题解
广度优先遍历
广度优先遍历也叫做层序遍历,也就是说优先将每一层的节点都遍历完毕后,才会遍历下一层,使用该种方式遍历的时候,如果该层中出现某节点左右节点都是空的(也就是叶子节点)时候,那么当前层数(从上到下依次递增)就是最小深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
// 如果根节点是空,则直接返回0
if (root == null) {
return 0;
}
// 如果根节点不为空,则将根节点放入队列中,使用队列完成广度优先遍历。
Queue<TreeNode> queue = new LinkedList<>();
// 将根节点入队
queue.offer(root);
// 根节点不为空的时候,深度(层级)一定从1开始。
int minDepth = 1;
// 队列不为空,则一直遍历。
while (!queue.isEmpty()) {
// size代表每一层
int size = queue.size();
// 弹出一层中的所有节点,并判断节点是否是叶子节点,如果是叶子节点,那么直接返回最小深度,如果不是叶子节点,将左右节点放入队列(左右节点肯定有一个不为空)
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
TreeNode left = poll.left;
TreeNode right = poll.right;
if (left == null && right == null) {
return minDepth;
}
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
}
}
// 每层遍历完毕后,如果未找到叶子节点,则层数(最小深度)加1
minDepth++;
}
return minDepth;
}
}
提交代码:
深度优先遍历
还有一种方法使用深度优先遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
// 如果左子树为空,则最小深度取决于右子树,反之成立
if (leftDepth == 0 || rightDepth == 0) {
return Integer.max(leftDepth, rightDepth) + 1;
}
return Integer.min(leftDepth, rightDepth) + 1;
}
}
提交结果如下: