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

相关推荐
眰恦37413 分钟前
数据结构--第六章图
数据结构·算法
2401_8628867822 分钟前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
luthane24 分钟前
python 实现armstrong numbers阿姆斯壮数算法
python·算法
楠枬27 分钟前
双指针算法
java·算法·leetcode
sjsjs1130 分钟前
【数据结构-差分】力扣1589. 所有排列中的最大和
数据结构·算法·leetcode
小川_wenxun1 小时前
优先级队列(堆)
java·开发语言·算法
孙小二写代码1 小时前
[leetcode刷题]面试经典150题之4删除有序数组中的重复项II(中等)
算法·leetcode·面试
tlsnzcel2 小时前
【java】常见限流算法原理及应用
java·算法
weixin_515033932 小时前
ccfcsp-202006(4、5)
c++·算法