题目要求

思路1
1.遍历一遍二叉树,将左边的结点对应创建一个右边的结点
2.用此方法空间复杂度O(n),并不是最优
思路2
1.将一个结点的左右子树进行交换,如果左子树还有左右结点,就再交换左子树的左右结点,以此递归下去。
2.用此方法的空间复杂度是O(1),不需要创建新的结点
代码实现
            
            
              cpp
              
              
            
          
          /**
 * struct TreeNode {
 *      int val;
 *      struct TreeNode *left;
 *      struct TreeNode *right;
 *      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        // write code here
        if (pRoot == nullptr)
            return nullptr;
        TreeNode* head = new TreeNode(pRoot->val);
        head->left = Mirror(pRoot->right);
        head->right = Mirror(pRoot->left);
        return head;
    }
};
/**
 * struct TreeNode {
 *      int val;
 *      struct TreeNode *left;
 *      struct TreeNode *right;
 *      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <cstdio>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        // write code here
        if(pRoot != nullptr)
        {
            TreeNode* temp = pRoot->left;
            pRoot->left = pRoot->right;
            pRoot->right = temp;
            Mirror(pRoot->left);
            Mirror(pRoot->right);
        }
        return pRoot;
    }
};