算法(TS):二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

上图二叉树的最大深度是3

解法一

使用递归。二叉树的最大深度是其左右子树的最大深度的最大值加一。

ts 复制代码
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxDepth(root: TreeNode | null): number {
    return root === null ? 0: Math.max(maxDepth(root.left),maxDepth(root.right)) + 1
    
};

时间复杂度O(n),空间复杂度O(hight),其中hight复杂度取决于树的高度,递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

解法二

广度优先遍历。用 depth 保存树的深度,初始值为 0,用一个队列 nodeList 维护树中当前层的全部节点,进入下一层时,上一层的节点已经从队列的全部取出,并且将 depth ++。

ts 复制代码
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxDepth(root: TreeNode | null): number {
    if (!root) return 0
    let depth = 0
    const nodeList = [root]
    while(nodeList.length) {
        let size = nodeList.length
        while(size>0) {
            const node = nodeList.shift()
            if(node.right) {
                nodeList.push(node.right)
            }

            if(node.left) {
                nodeList.push(node.left)
            }
            size--
        }
        depth++ 
    }
    return depth
};

时间复杂度O(n),空间复杂度取决于队列存储的元素数量,在最坏情况下会达到 O(n)。

相关推荐
To_OC6 小时前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
GreenTea6 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
fqq37 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
mCell9 小时前
用 Cordis 从零构建一个 Mini DeepSeek Harness
typescript·agent·deepseek
2501_906565129 小时前
数学之美探究
算法
oier_Asad.Chen10 小时前
【洛谷题解/AcWing题解/OI学习笔记】洛谷P2868【USACO07DEC】Sightseeing Cows G(01分数规划求最大比率)
算法·图论·spfa·二分·负环
满栀58510 小时前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
leisoo809711 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法
luj_176813 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
苏灿烤鱼14 小时前
公司**不可计算,就自己做操作系统
rust·typescript·agent