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

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;
    }
}
相关推荐
Jack_hsfs7 分钟前
第6章Spring 管理的是对象,还是对象的说明书?
java·后端·spring
Tairitsu_H9 分钟前
[C++高阶数据结构·图论上] 最小生成树:为什么“选边”和“选点”是两条路?
数据结构·c++·图论·最小生成树
十二同学啊22 分钟前
Python 工程化详解:项目结构、依赖管理、代码质量、测试与部署
java·开发语言·python
YIN_尹26 分钟前
【git原理与使用】git基本操作及底层原理(一)
java·git·elasticsearch
程序员飞哥36 分钟前
AI 编程额度怎么用才不浪费?
java·前端·后端
yh弓长41 分钟前
Spring MVC 的请求链路
java·spring·mvc
拆房老料42 分钟前
【第四部分:Agentic 智能体设计模式】17. Agent 路由模式详解:从意图识别到动态模型选择
java·设计模式·ai编程·策略模式
樱花落木兰1 小时前
Redis 消息队列的可靠性演进:从 List、Pub/Sub 到 Stream 消费者组,以及 8.x 版本改变了什么
java·开发语言·经验分享·redis·分布式·python·软件工程
wtblszn1 小时前
凹版印刷机智慧运维物联网系统方案
java·运维·物联网
Nuanyt1 小时前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针