Skip to content
本页目录

27-二叉树的镜像

题目描述

https://leetcode.cn/problems/er-cha-shu-de-jing-xiang-lcof

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

例如输入:

     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

注意:本题与主站 226 题相同:https://leetcode.cn/problems/invert-binary-tree/

思路1:递归1

递归构造左右节点 注意 newNode 一定要构造新的出来,否则直接引用原来的 root 去做操作,容易出错

实现代码

csharp
public class Solution {

    private TreeNode CopyNode(TreeNode node){
        if(node == null){
            return null;
        }
        TreeNode newNode = new TreeNode(node.val);
        newNode.left = CopyNode(node.right);
        newNode.right = CopyNode(node.left);
        return newNode;
    }

    public TreeNode MirrorTree(TreeNode root) {
        return CopyNode(root);
    }
}

思路2:递归2

直接在源节点上操作,注意需要定义变量 left 和 right 然后操作完成之后再赋值

参考代码

csharp
public class Solution {
    public TreeNode MirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }

        TreeNode left = MirrorTree(root.right);
        TreeNode right = MirrorTree(root.left);
        root.left = left;
        root.right = right;
        return root;
    }
}

复习:20220611

csharp
public class Solution {
    public TreeNode MirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        root.right = left;
        root.left = right;
        MirrorTree(root.left);
        MirrorTree(root.right);
        return root;
    }
}

Released under the MIT License.