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

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;
    }
}
相关推荐
1024肥宅4 分钟前
JavaScript 性能与优化:数据结构和算法
前端·数据结构·算法
我家领养了个白胖胖18 分钟前
SSE在Spring ai alibaba中同时使用Qwen和DeepSeek模型
java·后端·ai编程
仰泳的熊猫24 分钟前
1112 Stucked Keyboard
数据结构·c++·算法·pat考试
AI科技摆渡32 分钟前
GPT-5.2介绍+ 三步对接教程
android·java·gpt
猿与禅38 分钟前
Spring Boot 4.0 完整核心特性及实践指南
java·spring boot·后端·spring·重大升级·springboot4.0
运维@小兵1 小时前
Spring-AI系列——Tool Calling获取当前时间
java·后端·spring
认真敲代码的小火龙1 小时前
【JAVA项目】基于JAVA的养老院管理系统
java·开发语言·课程设计
he___H1 小时前
滑动窗口一题
java·数据结构·算法·滑动窗口
AI科技星1 小时前
统一场论质量定义方程:数学验证与应用分析
开发语言·数据结构·经验分享·线性代数·算法
扶苏-su1 小时前
Java---事件处理机制
java·开发语言