当前位置: 首页 > article >正文

LeetCode 解题思路 19(Hot 100)

在这里插入图片描述

解题思路(递归):

  1. 终止条件: 若节点为空,返回深度0。
  2. 递归步骤: 分别计算左子树和右子树的最大深度,取较大者并加1(当前节点)。

Java代码:

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);
    }
}

复杂度分析:

  • 时间复杂度: ​O(n), 需访问每个节点一次。
  • 空间复杂度: 递归调用栈的深度取决于树的高度 h,最坏情况(树为链表)空间复杂度为 ​O(n),平衡树时为 ​O(log n)。

解题思路(BFS):

  1. 层次遍历: 逐层处理节点,每处理一层深度加1。若节点为空,返回深度0。
  2. 队列实现: 利用队列存储当前层所有节点,循环处理直至队列为空。

Java代码:

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()) {
            depth++;
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return depth;
    }
}

复杂度分析:

  • 时间复杂度: ​O(n), 需访问每个节点一次。
  • 空间复杂度: 队列最多存储一层节点,最坏情况(完全二叉树)空间复杂度为 ​O(n)。

在这里插入图片描述

解题思路(递归):

  1. 终止条件: 当前节点为空时返回 null,当前节点没有子树时返回当前节点。
  2. 递归步骤: 递归翻转左子树和右子树,然后交换当前节点的左子节点和右子节点。

Java代码:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        if (root.left == null && root.right == null) return root;

        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        root.left = right;
        root.right = left;

        return root;
    }
}

复杂度分析:

  • 时间复杂度: ​O(n),需访问每个节点一次。
  • 空间复杂度: 递归调用栈的深度为树的高度 h,最坏情况(链状树)空间复杂度为 ​O(n)。

http://www.kler.cn/a/591884.html

相关文章:

  • llama-factory微调deepseek-r1:1.5b
  • HarmonyOS Next实战教程:实现中间凹陷的异形tabbar
  • MrRobot靶机详细解答
  • ubuntu安装milvus向量数据库
  • 玩转RAG应用:如何选对Embedding模型?
  • 结合使用 OpenCV 和 TensorFlow进行图像识别处理
  • Linux信号入门
  • DeepSeek:AI 搜索引擎的革新者?
  • 【数据分享】1999—2023年地级市固定资产投资和对外经济贸易数据(Shp/Excel格式)
  • 浅谈鸿蒙跨平台开发框架ArkUI-X
  • 再学:call与delegatecall、call转账 Bank合约
  • dockerfile 编写入门
  • 2025年渗透测试面试题总结- 腾讯科恩实验室实习 二面(题目+回答)
  • 采购与供应链项目建议书(46页PPT)(文末有下载方式)
  • 从bootloader跳到APP需要几步?
  • C# Exe + Web 自动化 (BitComet 绿灯 自动化配置、设置)
  • 如何创建并保存HTML文件?零基础入门教程
  • 深入理解 Vue 的响应式原理:从 Vue 2 到 Vue 3
  • Tailwind CSS 学习笔记(一)
  • LeetCode 第11题~第13题