1.题目描述:
给定一个二叉树,找出其最小深度,最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
2.BFS层级遍历(迭代):寻找最小深度,通过队列层级遍历,找到第一个节点不存在左右子节点即可。时间复杂度O(n),但是一旦找到直接return时间上会快一些,空间复杂度最差O(n)。
/**
* 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;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int count = 0;
while(!queue.isEmpty()){
int size = queue.size();
while(size > 0){
TreeNode node = queue.poll();
size--;
if(node.left == null && node.right == null) return count + 1;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
count++;
}
return 0;
}
}
二刷层序遍历:
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int depth = 0;
boolean flag = false;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode temp = queue.poll();
size--;
if (temp.left != null) queue.offer(temp.left);
if (temp.right != null) queue.offer(temp.right);
if (temp.left == null && temp.right == null) {
flag = true;
break;
}
}
depth++;
if (flag) break;
}
return depth;
}
}
3.递归:
跟求leetcode104. 二叉树的最大深度有所不同,在递归左右子节点之前,需要判断左右子节点是否为空,若左子节点为空,如果不判断的话在递归调用时会返回0,但是此时无法确定右子节点是否为空,不能保证此节点为叶子节点。正确代码如下,三种写法本质上一样,时间复杂度O(n),空间复杂度最差O(n)。
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null) return minDepth(root.right) + 1;
if (root.right == null) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null || root.right == null) return minDepth(root.left) + minDepth(root.right) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
if (left == 0 || right == 0) return left + right + 1;
return Math.min(left, right) + 1;
}
}