剑指offer-18、⼆叉树的镜像

题⽬描述

操作给定的⼆叉树,将其变换为源⼆叉树的镜像。

⼆叉树的镜像定义:源⼆叉树

思路及解答

递归

采用后序遍历(左-右-根)的方式递归访问每个节点:

  1. 递归处理左子树
  2. 递归处理右子树
  3. 访问根节点并交换其左右子树
java 复制代码
public TreeNode mirrorTree(TreeNode root) {
    if (root == null) return null;
    // 先递归处理子树
    TreeNode left = mirrorTree(root.left);
    TreeNode right = mirrorTree(root.right);
    // 再交换左右子树
    root.left = right;
    root.right = left;
    return root;
}

或者采用前序遍历(根-左-右)的方式递归访问每个节点:

  1. 访问根节点并交换其左右子树
  2. 递归处理左子树
  3. 递归处理右子树
java 复制代码
public TreeNode mirrorTree(TreeNode root) {
    if (root == null) {
        return null;
    }
    // 交换左右子树
    TreeNode temp = root.left;
    root.left = root.right;
    root.right = temp;
    // 递归处理左右子树
    mirrorTree(root.left);
    mirrorTree(root.right);
    return root;
}
  • 时间复杂度:O(n),每个节点只被访问一次
  • 空间复杂度:O(h),h为树的高度,递归栈空间消耗

迭代

利用队列实现广度优先搜索(BFS):

  1. 将根节点加入队列
  2. 取出队首节点并交换其左右子树
  3. 将非空的左右子节点加入队列
  4. 重复直到队列为空
java 复制代码
public TreeNode mirrorTree(TreeNode root) {
    if (root == null) return null;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();
        // 交换左右子树
        swap(node);
        // 将子节点加入队列
        if (node.left != null) queue.offer(node.left);
        if (node.right != null) queue.offer(node.right);
    }
    return root;
}

public void swap(TreeNode root) {
    TreeNode temp = root.left;
    root.left = root.right;
    root.right = temp;
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n),最坏情况下需要存储所有节点
相关推荐
lUie INGA2 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
geBR OTTE2 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu2 小时前
博客系统UI自动化测试报告
java
Aurorar0rua3 小时前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy4 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
布谷歌4 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
eLIN TECE4 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
老神在在0015 小时前
Spring Bean 的六种作用域详解
java·后端·spring
仙草不加料5 小时前
互联网大厂Java面试故事实录:三轮场景化技术提问与详细答案解析
java·spring boot·微服务·面试·aigc·电商·内容社区
程序员老邢5 小时前
【技术底稿 19】Redis7 集群密码配置 + 权限锁死 + 磁盘占满连锁故障真实排查全记录
java·服务器·经验分享·redis·程序人生·微服务