题目:
题解一:层序遍历
通过层序遍历每一层的节点,当遍历到叶子节点,该叶子节点的深度即为二叉树的最小深度,时间复杂度:O(n)
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int depth = 1;
while (!queue.isEmpty()) {
// 遍历当前层的节点
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
// 如果当前节点左右子树都为空,说明当前为叶子节点,直接返回叶子节点的深度
if (node.left == null && node.right == null) {
return depth;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
depth++;
}
return 0;
}
题解二:递归遍历
递归遍历左右子树,取左右子树最小的的深度+1。
递归边界:
1.当root左右孩子都为null时,返回1
2.当root左右孩子有一个为null时,返回不为null的孩子节点深度
3.当root左右孩子都不为null,返回左右孩子较小深度
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
// 当左右孩子有null时,必定其深度为0,所以这里需要取左右孩子较大的深度
if (root.left == null || root.right == null) {
return Math.max(leftDepth, rightDepth) + 1;
}
// 左右孩子都不为null,取最小深度
return Math.min(leftDepth, rightDepth) + 1;
}
当左右孩子为null时,其深度为0,所以代码可以简写直接返回 leftDepth + rightDepth + 1
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
return root.left == null || root.right == null ? leftDepth + rightDepth + 1 : Math.min(leftDepth, rightDepth) + 1;
}
时间复杂度:O(n)