当前位置: 首页 > news >正文

Day21:二叉树的深度

某公司架构以二叉树形式记录,请返回该公司的层级数。

示例 1:

输入:root = [1, 2, 2, 3, null, null, 5, 4, null, null, 4]
输出: 4
解释: 上面示例中的二叉树的最大深度是 4,沿着路径 1 -> 2 -> 3 -> 4 或 1 -> 2 -> 5 -> 4 到达叶节点的最长路径上有 4 个节点。

LCR 175. 计算二叉树的深度 - 力扣(LeetCode)

层序遍历:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int calculateDepth(TreeNode root) {
        if(root == null){
            return 0;
        }

        ArrayDeque<TreeNode> queue  = new ArrayDeque<>();
        queue.offer(root);
        int level = 0;
        while(!queue.isEmpty()){
            int levelSize = queue.size();
            for(int i = 0; i< levelSize; i++){
                TreeNode p = queue.poll();
                if(p.left != null){
                    queue.offer(p.left);
                }
                if(p.right != null){
                    queue.offer(p.right);
                }
            }
            level++;
        }
        return level;
    }
}

更快的算法:后序遍历

此树的深度和其左(右)子树的深度之间的关系。显然,此树的深度 等于 左子树的深度 与 右子树的深度 中的 最大值 +1 。

class Solution {
    public int calculateDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.max(calculateDepth(root.left), calculateDepth(root.right)) + 1;
    }
}

相关文章:

  • 知行之桥EDI系统应用程序目录切换指南(Windows与跨平台版)
  • Java-SpringBootWeb入门、Spring官方脚手架连接不上解决方法
  • 使用Three.js渲染器创建炫酷3D场景
  • 74HC04(反相器)和74HC14(反相器、施密特触发器)的区别
  • 【项目】幸运抽奖 测试报告
  • 怎么查看linux是Ubuntu还是centos
  • Compose 实践与探索十五 —— 自定义触摸
  • Python 应用部署云端实战指南 —— AWS、Google Cloud 与 Azure 全解析
  • 学习threejs,使用TextGeometry文本几何体
  • MySQL数据库入门到大蛇尚硅谷宋红康老师笔记 高级篇 part11
  • Springboot各版本与Java JDK的对应关系及JDK商用版本
  • 【JavaWeb学习Day27】
  • 洛谷 P2157 [SDOI2009] 学校食堂
  • C++从入门到实战(六)类和对象(第二部分)C++成员对象及其实例化,对象大小与this详解
  • pytorch 网络结构可视化Netron安装使用方法(已解决)
  • 人力资源管理基于SpringBootSSM框架
  • 基于NSGA2算法的无人机航迹规划算法
  • 【MyDB】一个仿照MySQL的轮子项目系列文章汇总
  • springboot项目,指定用alibaba连接池所需要的配置
  • 《模型思维》第二十六章 “学习模型” 总结
  • 复旦建校120周年大型义诊举行,百余名专家服务市民超三千人次
  • 茅台总经理到访五粮液:面对白酒行业周期性调整,需要团结一心的合力
  • 尹锡悦宣布退出国民力量党
  • 霍步刚任辽宁沈阳市委书记
  • 科普|认识谵妄:它有哪些表现?患者怎样走出“迷雾”?
  • 证监会发布《上市公司募集资金监管规则》,6月15日起施行