JAVA练习37-二叉树的镜像

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:
       4
     /    \
   2      7
  /  \    /  \
1    3 6    9

镜像输出:
       4
     /    \
   7      2
  /  \    /  \
9    6 3   1

示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:

  • 0 <= 节点个数 <= 1000

分析:

这道题的思路就在于交换一个节点的节点的左右节点,然后再交换下一个节点的左右节点,重点在于遍历这些节点,我想到的有广度优先搜索(BFS)和深度优先搜索(DFS)。

方法1:BFS+队列

时间复杂度:O(n)
空间复杂度:O(n) 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        //创建队列
        Deque<TreeNode> queue = new ArrayDeque<>();
        //入栈头节点
        queue.offerLast(root);
        while(!queue.isEmpty()){
            //出栈一个节点
            TreeNode node = queue.pollFirst();
            //交换左右节点
            TreeNode left = node.left;
            node.left = node.right;
            node.right = left;
            //入栈左右节点
            if(node.left != null){
                queue.offerLast(node.left);
            }
            if(node.right != null){
                queue.offerLast(node.right);
            }
        }
        return root;
    }
}

方法2:DFS+递归

时间复杂度:O(n)
空间复杂度:O(n) 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        //空树判断
        if(root == null){
            return null;
        }
        //交换左右节点
        TreeNode left = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(left);
        return root;
    }
}

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什巳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值