前端算法锦囊 二叉树

100 阅读2分钟

#二叉树的最大深度(Maximum Depth of Binary Tree)

题目描述:

给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

示例:

输入:
    3
   / \
  9  20
    /  \
   15   7

输出:3
解释:最长路径为 3 -> 20 -> 153 -> 20 -> 7,深度为 3

解题思路:

  1. 递归法
    • 二叉树的深度等于其左子树和右子树深度的最大值加 1。
    • 递归终止条件:如果当前节点为空,返回深度 0。
  2. 迭代法(广度优先搜索 BFS)
    • 使用队列进行层序遍历,每遍历一层,深度加 1。

代码实现(递归法):

function maxDepth(root) {
    if (root === null) return 0; // 递归终止条件
    const leftDepth = maxDepth(root.left); // 计算左子树深度
    const rightDepth = maxDepth(root.right); // 计算右子树深度
    return Math.max(leftDepth, rightDepth) + 1; // 返回最大深度
}

// 测试
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}

const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);

console.log(maxDepth(root)); // 输出 3

代码实现(迭代法,BFS):

function maxDepth(root) {
    if (root === null) return 0; // 边界条件

    const queue = [root]; // 初始化队列
    let depth = 0; // 初始化深度

    while (queue.length > 0) {
        const levelSize = queue.length; // 当前层的节点数
        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift(); // 取出队头节点
            if (node.left !== null) queue.push(node.left); // 将左子节点加入队列
            if (node.right !== null) queue.push(node.right); // 将右子节点加入队列
        }
        depth++; // 深度加 1
    }

    return depth; // 返回最大深度
}

// 测试
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);

console.log(maxDepth(root)); // 输出 3

复杂度分析:

  • 时间复杂度:O(n),其中 n 是二叉树的节点数。每个节点都会被访问一次。
  • 空间复杂度:
    • 递归法:O(h),其中 h 是二叉树的高度。递归调用栈的深度为树的高度。
    • 迭代法:O(n),队列中最多存储一层的节点数。