二叉树的最大深度(遍历思想+分解思想)

Problem: 104. 二叉树的最大深度

文章目录

题目描述

思路

遍历思想(实则二叉树的先序遍历)

1.欲望求出最大的深度,先可以记录一个变量res,同时记录每次当前节点所在的层数depth

2.在递的过程中,每次递一层,也即使当前又往下走了一层,则depth++,当到达叶子节点时,比较并取出max【res, depth】

3.在归的过程中,因为是在往上层归,则depth--;

4.返回最终的res即可

分解思想

1.要求整个树的最大深度则可以分解其为求去当前节点的左右子树的最大深度再加当前节点的高度1

复杂度

二者均为

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);最坏空间复杂度

Code

遍历思想

java 复制代码
/**
/**
 * 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 {
    // recode the maximum depth 
    int res = 0;
    // recode the depth of the traversed node
    int depth = 0;
    public int maxDepth(TreeNode root) {
        traverse(root);
        return res;
    }

    public void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        depth++;
        if (root.left == null && root.right == null) {
            res = Math.max(res, depth);
        }
        traverse(root.left);
        traverse(root.right);
        depth--;
    }
}

分解思想

java 复制代码
 class Solution {
    // Definition: Given the root node, return the maximum depth of the binary tree
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // calculate the maximum depth of the left and right subtrees
        int leftMax = maxDepth(root.left);
        int rightMax = maxDepth(root.right);
        // The maximum depth of the entire tree is
        // the maximum of the left and right subtree
        // plus one for the root node itself
        int res = Math.max(leftMax, rightMax) + 1;

        return res;
    }
}
相关推荐
Codiggerworld7 小时前
从字节码到JVM:深入理解Java的“一次编写,到处运行”魔法
java·开发语言·jvm
_codemonster8 小时前
配置Tomcat时为啥要配置Artifacts
java·tomcat·firefox
无心水8 小时前
2025,一路有你!
java·人工智能·分布式·后端·深度学习·架构·2025博客之星
无聊的小坏坏8 小时前
一文讲通:二分查找的边界处理
数据结构·c++·算法
m0_528749008 小时前
C语言错误处理宏两个比较重要的
java·linux·算法
独自破碎E8 小时前
BISHI43 讨厌鬼进货
android·java·开发语言
MX_93598 小时前
Spring xml 方式整合第三方框架总结加案例
xml·java·spring
化学在逃硬闯CS8 小时前
Leetcode110.平衡二叉树
数据结构·c++·算法·leetcode
没有bug.的程序员8 小时前
服务网格(Istio)与传统微服务深度对垒:流量治理内核、代码侵入性博弈与运维收益实战指南
java·运维·微服务·istio·流量治理内核·代码侵入性
该叫啥8 小时前
Spring Bean 生命周期
java·spring·servlet