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

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;
    }
}
相关推荐
brave_zhao14 分钟前
关于javafx下打开postman无法正常关闭postman的问题
java·测试工具·postman
攻心的子乐17 分钟前
Spring IOC 源码
java·后端·spring
Sirens.18 分钟前
Java异常处理解析:从防御式编程到自定义异常类
java·开发语言·笔记·学习·github·javac
千寻技术帮28 分钟前
10351_基于Springboot的二手交易平台
java·spring boot·mysql·毕业设计·源码·代码·二手交易
alonewolf_9938 分钟前
Spring依赖注入源码深度解析:从@Autowired到@Resource的完整实现机制
java·后端·spring
雪碧聊技术44 分钟前
如何界定人工智能和java开发二者的关系?
java·人工智能·二者关系界定
Chase_______1 小时前
【JAVA基础指南(四)】快速掌握类和对象
java·开发语言
muxin-始终如一1 小时前
Maven HTTP 仓库被阻止问题解决总结
java·http·maven
武斌1 小时前
需要独立的作业队列?看看Quartz增强框架Quartz Plus
java·spring boot·后端
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——两数之和
数据结构·算法·leetcode·力扣·结构与算法