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

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;
    }
}
相关推荐
ShineWinsu5 分钟前
对于C++中unordered_map的详细介绍
数据结构·c++·算法·面试·stl·哈希表·unordered_map
敲个大西瓜8 分钟前
JAVA 并发编程
java·并发编程
vHelios38 分钟前
【电商项目】商品服务模块的问题解决与代码逻辑思考
java·sql·mybatis
rannn_11143 分钟前
【力扣hot100】238、41、73题解
java·算法·leetcode·开发
lingran__1 小时前
C++ 高阶数据结构:AVL 树万字详解|原理、四种旋转、key‑value 实现、调试校验、set/map/红黑树 底层前置知识
数据结构·c++·二叉搜索树·平衡二叉树·avl树·红黑树前置
今天的砖头有点烫手啊1 小时前
Spring Boot
java·人工智能
疯狂打码的少年2 小时前
【数据结构】顺序表 vs 链表的对比与选择
数据结构·笔记·链表
码农颜11 小时前
5.4.1 锁分类
java·数据库·mysql
wabs66611 小时前
关于图论【最短路径之Dijkstra算法(堆优化版)|卡码网47.参加科学大会的思考】
数据结构·算法·图论·优先级队列·邻接表·小顶堆·卡码网
linux-hzh12 小时前
百日算法修炼 · Day 03
java·算法