104.二叉树的最大深度

题目

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

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

python

法一、后序遍历

  • 后序遍历+递归实现:此树的深度 等于 左子树的深度 与 右子树的深度中的 最大值+1
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root: return 0   #终止条件: 当 root​ 为空,说明已越过叶节点,因此返回 深度0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

法二、层序遍历

  • 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root: return 0  #当 root​ 为空,直接返回 深度0 
        queue, res = [root], 0 #初始化队列(加入根节点root),计数器res=0
        while queue:#当队列不空时执行:
            tmp = []   #初始化一个空列表 tmp ,用于临时存储下一层节点。
            for node in queue:   #遍历 queue 中的各节点 node
                if node.left: tmp.append(node.left)  #左子节点加入 tmp
                if node.right: tmp.append(node.right)   #右子节点加入 tmp
            queue = tmp  #将下一层节点赋值给 queue
            res += 1  #层数加 1
        return res

javascript

法一、后序遍历

  • 后序遍历+递归实现:此树的深度 等于 左子树的深度 与 右子树的深度中的 最大值+1
var maxDepth = function(root) {
    if (root === null) return 0; // 如果根节点为 null,返回 0

    // 递归计算左右子树的深度
    let leftDepth = maxDepth(root.left);
    let rightDepth = maxDepth(root.right);

    // 返回当前节点的深度
    return Math.max(leftDepth, rightDepth) + 1;
};

法二、层序遍历

  • 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。
var maxDepth = function(root) {
    if(root===null) return 0
    let queue=[root]
    let res=0
    while(queue.length>0){
        let n=queue.length
        res++
        for(let i=0;i<n;i++){
            let cur_node=queue.shift()
            if(cur_node.left) queue.push(cur_node.left)
            if(cur_node.right) queue.push(cur_node.right)
        }
    }
    return res
};
posted @   Frommoon  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示