111. 二叉树的最小深度
描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
示例
示例1
输入:root = [3,9,20,null,null,15,7]
输出:2
示例2
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
链接
https://leetcode.cn/problems/minimum-depth-of-binary-tree/
解题思路
思路一: 递归/深度优先搜索
- 叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点
- 当 root 节点左右孩子都为空时,返回 1
- 当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度
- 当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (root === null) return 0;
let m1 = minDepth(root.left);
let m2 = minDepth(root.right);
//1.如果左孩子和右孩子有为空的情况,直接返回m1+m2+1
//2.如果都不为空,返回较小深度+1
return root.left == null || root.right == null ? m1 + m2 + 1 : Math.min(m1,m2) + 1;
};
时间复杂度: O(n)
空间复杂度: O(height), 其中 height 表示二叉树的高度。递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。
或者以下代码:
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
if (root === null) return 0;
if (root.left == null && root.right == null) {
return 1;
}
let min_depth = 100001;
if (root.left != null) {
min_depth = Math.min(minDepth(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth(root.right), min_depth);
}
return min_depth + 1;
}
思路二: 广度优先搜索
利用队列, 且队列里存放的是「当前层的所有节点」。每次拓展下一层的时候,不同于广度优先搜索的每次只从队列里拿出一个节点,我们需要将队列里的所有节点都拿出来进行拓展,这样能保证每次拓展完的时候队列里存放的是当前层的所有节点,即我们是一层一层地进行拓展,最后我们用一个变量 depth 来维护拓展的次数,该二叉树的最小深度即为 depth。
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function (root) {
if (root === null) return 0;
let queue = [root], depth = 0;
while(queue.length) {
let length = queue.length;
depth++;
while(length) {
let node = queue.shift();
if (node.left !== null) queue.push(node.left);
if (node.right !== null) queue.push(node.right);
// 如果左右节点都是null(在遇见的第一个leaf节点上),则该节点深度最小
if (node.left === null && node.right === null) {
return depth;
}
length--;
}
}
return depth;
}
参考资料
https://leetcode.cn/problems/minimum-depth-of-binary-tree/solution/li-jie-zhe-dao-ti-de-jie-shu-tiao-jian-by-user7208/
https://leetcode.cn/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode-solutio/