算法(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)。

相关推荐
董董灿是个攻城狮4 小时前
AI视觉连载8:传统 CV 之边缘检测
算法
AI软著研究员11 小时前
程序员必看:软著不是“面子工程”,是代码的“法律保险”
算法
FunnySaltyFish11 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
颜酱12 小时前
理解二叉树最近公共祖先(LCA):从基础到变种解析
javascript·后端·算法
时光不负努力14 小时前
编程常用模式集合
前端·javascript·typescript
时光不负努力14 小时前
ts+vue3开发规范
vue.js·typescript
时光不负努力15 小时前
typescript常用的dom 元素类型
前端·typescript
时光不负努力15 小时前
TS 常用工具类型
前端·javascript·typescript
地平线开发者1 天前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮1 天前
大模型连载2:初步认识 tokenizer 的过程
算法