2025年- H25-Lc133- 104. 二叉树的最大深度(树)---java版

1.题目描述

2.思路

返回左右子树中,最高高度的子树,高度从0开始计数。

3.代码实现

java 复制代码
 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;
     }
 }

public class H104 {
    public int maxDepth(TreeNode root) {

        if(root==null)
        {
            return 0;//如果节点为空,返回高度0
        }
        else {
            int  leftree=maxDepth (root.left);
            int  rightree=maxDepth(root.right);
            return Math.max(leftree,rightree)+1;//高度从0开始计算,所以此处高度+1
        }

    }
    public static void main(String[] args)
    {
        H104 test11=new H104();
        //1->null->2
        TreeNode node1=new TreeNode(2);
        TreeNode root=new TreeNode(1,null,node1);

        int depth=test11.maxDepth(root);
        System.out.println("二叉树的高度:"+depth);



    }
}
相关推荐
学长毕设8 小时前
基于SpringBoot的实验室资产管理系统
java·spring boot·后端
C^h8 小时前
c++ string
开发语言·c++
raindayinrain9 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的9 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao9 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
zzu123zsw10 小时前
从臃肿的模板调用到声明式契约:深入 UniHttp 动态代理与多渠道生命周期扩展
java·spring boot·microsoft·unihttp
学逆向的10 小时前
C 局部静态变量
c语言·开发语言·网络安全
大都督会赢的10 小时前
C++第一节课
开发语言·c++
“AI国潮设计-小江”10 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
源码集结号10 小时前
云诊所门诊系统源码,基于SpringBoot+Vue.js架构,支持多租户设计与Docker容器化部署
java·spring boot·源码·医院信息系统·门诊系统·诊所系统