力扣104. 二叉树的最大深度(java,DFS,BFS解法)

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

文章目录

思路和解法

DFS

递归处理,退出条件为节点为空,归的过程每次取出当前节点左右子树的最大深度加一

BFS

经典的借助一个队列实现的BFS,用一个变量记录当前的最大层数,在循环实现出队当前节点和添加当前层节点的下一层后将最大层数加一

复杂度

DFS

  • 时间复杂度:

O ( n ) O(n) O(n)

  • 空间复杂度:

O ( n ) O(n) O(n)

BFS

  • 时间复杂度:

O ( n ) O(n) O(n)

  • 空间复杂度:

O ( n ) O(n) O(n)

Code

DFS

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 {
    //DFS
    //Time Complexity: O(n)
    //Space Complexity: O(n) 
    public int maxDepth(TreeNode root) {
        //退出条件
        if (root == null) return 0;
        return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
}

BFS

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 {
    //BFS
    //Time Complexity: O(n)
    //Space Complexity: O(n)
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        queue.add(root);
        //记录层数
        int level = 0;
        while (!queue.isEmpty()) {
            int curLevelSize = queue.size();
            for (int i = 0;i < curLevelSize; ++i) {
                TreeNode curLevelNode = queue.poll();
                if (curLevelNode.left != null) {
                    queue.add(curLevelNode.left);
                }
                if (curLevelNode.right != null) {
                    queue.add(curLevelNode.right);
                }
            }
            //层数加一
            level++;
        }
        return level;
    }
}
相关推荐
艾莉丝努力练剑24 分钟前
【C++:异常】C++ 异常处理完全指南:从理论到实践,深入理解栈展开与最佳实践
java·开发语言·c++·安全·c++11
武子康26 分钟前
Java-184 缓存实战:本地缓存 vs 分布式缓存(含 Guava/Redis 7.2)
java·redis·分布式·缓存·微服务·guava·本地缓存
小马爱打代码6 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
小坏讲微服务7 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z897 小时前
springboot 异步操作
java·spring boot·mybatis
i***13247 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白7 小时前
后端:SpringMVC
java
IT_Octopus7 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88997 小时前
Spring详解
java·后端·spring