跳至主要內容

Mr.He大约 1 分钟

求最小深度有两种常用的解法:深度优先搜索 (DFS) 和 广度优先搜索 (BFS)

解法一:广度优先搜索 (BFS)

/**
 * 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;

    // 使用队列进行广度优先遍历
    const queue = [root];
    let depth = 0;

    while (queue.length) {
        depth++; // 进入新的一层,深度加 1
        
        // 当前层的节点数量
        const levelSize = queue.length;
        
        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift(); // 取出队首节点

            // 如果当前节点是叶子节点(没有左右子节点),直接返回当前深度
            if (!node.left && !node.right) {
                return depth;
            }

            // 将子节点加入队列
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }
    }
    // return depth;
};

解法二:深度优先搜索 (DFS)

思路:递归计算左右子树的最小深度。
注意点:如果左子树为空,不能直接取 Math.min(0, 右子树深度),因为根据定义,最小深度是根节点到叶子节点的距离。如果一边为空,只能走另一边。

/**
 * @param {TreeNode} root
 * @return {number}
 */
var minDepth = function(root) {
    if (!root) return 0;

    // 1. 如果左子树为空,返回右子树的最小深度 + 1
    if (!root.left) return minDepth(root.right) + 1;
    
    // 2. 如果右子树为空,返回左子树的最小深度 + 1
    if (!root.right) return minDepth(root.left) + 1;
    
    // 3. 如果左右子树都不为空,返回两者较小值 + 1
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
};