leetcode-二叉树的镜像-91

题目要求

思路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;
    }
};
相关推荐
声声codeGrandMaster几秒前
线性回归实战下与深度学习概念
深度学习·算法·线性回归
sin_hielo9 分钟前
leetcode 2092(排序+bfs)
算法·leetcode·宽度优先
C雨后彩虹20 分钟前
斗地主之顺子
java·数据结构·算法·华为·面试
鸽鸽程序猿33 分钟前
【刷题册】二
算法
CoderCodingNo42 分钟前
【GESP】C++四级真题 luogu-B4416 [GESP202509 四级] 最长连续段
开发语言·c++·算法
xjxijd43 分钟前
工业元宇宙 IDC 支撑:数字孪生算法 + 边缘服务器,生产调度响应速度提 3 倍
运维·服务器·算法
a程序小傲1 小时前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
1024肥宅1 小时前
工程化工具类:模块化系统全解析与实践
前端·javascript·面试
想用offer打牌1 小时前
面试官问Redis主从延迟导致脏数据读怎么解决?
redis·后端·面试
鱼鱼块1 小时前
从零搭一个 Vue 小家:用 Vite + 路由轻松入门现代前端开发
vue.js·面试·前端框架