题目链接:111. 二叉树的最小深度
题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 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
文章讲解:代码随想录
视频讲解:看起来好像做过,一写就错! | LeetCode:111.二叉树的最小深度_哔哩哔哩_bilibili
题解1:后序遍历
首先先理解二叉树的深度和高度:
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)。
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)。
根节点的最小高度就是二叉树的最小深度。
思路:使用后序遍历,先遍历左子树找出左子树的最小深度(如果有左孩子),再遍历右子树找出右子树的最小深度(如果有右孩子),最后比较将小的一方加1,即为整个二叉树的最小深度。
注意与104. 二叉树的最大深度的不同再于需要判断根节点是否有左子树和右子树。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (!root) {
return 0;
}
if (root.left && root.right) {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
if (root.left) {
return minDepth(root.left) + 1;
}
if (root.right) {
return minDepth(root.right) + 1;
}
return 1;
};
分析:时间复杂度为 O(n),空间复杂度为 O(logn)。
题解2:前序遍历
思路:使用前序遍历,求出每个叶子节点的深度,其中最小的深度即为二叉树的最小深度。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (!root) {
return 0;
}
let res = Number.MAX_VALUE;
const preorder = function (node, depth) {
// 遍历到叶子节点,即可记录叶子节点的深度
if (!node.left && !node.right) {
res = depth < res ? depth : res; // 中
return;
}
if (node.left) {
preorder(node.left, depth + 1); // 左
}
if (node.right) {
preorder(node.right, depth + 1); // 右
}
}
preorder(root, 1);
return res;
};
分析:时间复杂度为 O(n),空间复杂度为 O(logn)。
题解3:层序遍历
思路:使用层序遍历,记录节点的深度,遇到的第1个叶子节点的深度即为二叉树的最小深度。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
let depth = 0;
const queue = [];
if (root) {
queue.push(root);
}
while (queue.length > 0) {
depth++;
let size = queue.length;
while (size--) {
const node = queue.shift();
if (!node.left && !node.right) {
return depth; // 遇到的第1个叶子节点的深度即为整个二叉树的最小深度
}
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
return depth;
};
分析:时间复杂度为 O(n),空间复杂度为 O(n)。
收获
学会了通过二叉树的多种遍历方式来求二叉树的最小深度,在细节处理方面比二叉树的最大深度要进行是否有左右孩子的界限判断。