剑指offer:二叉树的镜像

剑指offer:二叉树的镜像,第1张

剑指offer:二叉树的镜像

文章目录
      • 分析
      • 题目来源

分析


思路:

可以发现,对于任意一个结点来说,左孩子和右孩子(只要有的话)都是互换的。

时间复杂度:O(n),每个结点遍历一遍

ac代码

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (root == nullptr) return nullptr;
        // 交换左右孩子(这里空指针也参与交换,因为swap交换的是指针)
        swap(root->left, root->right);
        // 递归遍历即可
        mirrorTree(root->left);
        mirrorTree(root->right);
        return root;
    }
};
题目来源

https://www.acwing.com/problem/content/37/

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5691364.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存