每天 3 分钟,走上算法的逆袭之路。
GitHub: https://github.com/meteor1993/LeetCode
Gitee: https://gitee.com/inwsy/LeetCode
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:?叶子节点是指没有子节点的节点。
示例:
给定二叉树?[3,9,20,null,null,15,7],
3
/ 9 20
/ 15 7
返回它的最小深度 ?2 。
今天做题的时候才看到,我昨天竟然跳过了一道题,我自己都没发现。
这道题看了以后总感觉前面做过,果然我往前翻了翻,看到前面第 22 天做的题是求最大深度,这道题是求最小深度。
二叉树求最小深度,我第一个想法就是通过迭代来做,一层一层的做循环,每循环一层,就看下这一层有没有存在叶子节点(左右子树都是 null )的节点,如果有,就接着往下循环,如果没有,那就可以直接返回了。
解题流程上面已经讲得很清楚了,下面是代码实现:
public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
if (node.left == null && node.right == null) {
return depth + 1;
}
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
size--;
}
++depth;
}
return depth;
}
这段代码就不解释了吧,经常看的同学应该都很清楚了,使用队列循环是循环二叉树最基本的方案。
上面这个迭代的方案实际上是对广度优先搜索的一种实现,而深度优先搜索的实现,则是由递归来进行实现的。
public int minDepth_1(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int min_depth = Integer.MAX_VALUE;
if (root.left != null) {
min_depth = Math.min(minDepth_1(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth_1(root.right), min_depth);
}
return min_depth + 1;
}
使用深度优先搜索,实际上我们是计算了每一个非叶子节点的左右子树的最小深度,然后我们把取得的最小深度返回就结束了。
原文:https://www.cnblogs.com/babycomeon/p/13563107.html