剑指 Offer 27. 二叉树的镜像

本文详细介绍了四种不同的方法来实现二叉树的翻转,包括递归和BFS层序遍历等,提供了清晰的C++代码示例,帮助读者深入理解二叉树的镜像操作。

同力扣226 :翻转二叉树
题目:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。

二叉树的镜像

方法一:引入交换结点temp+递归

推荐函数代码一:

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root)
        {
            return NULL;
        }

        TreeNode *temp=root->left;
        root->left=root->right;
        root->right=temp;
        mirrorTree(root->left);
        mirrorTree(root->right);
        return root;
    }
};

函数代码二:

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root) return nullptr;
        mirrorTree(root->left);
        mirrorTree(root->right);
        swap(root->left, root->right);
        return root;
    }
};

函数代码三:

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (root == NULL) {
            return NULL;
        }
        swap(root->left, root->right);
        mirrorTree(root->left);
        mirrorTree(root->right);
        return root;
    }
};

函数代码四:

public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root)
        {
            return NULL;
        }

        TreeNode *temp=root->left;
        root->left=mirrorTree(root->right);
        root->right=mirrorTree(temp);
        return root;
    }
};

方法二:BFS+队列+层序遍历

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root)
        {
            return NULL;
        }

        queue<TreeNode *>q;
        q.push(root);

        while(!q.empty())
        {
            TreeNode *p=q.front();
            q.pop();
            if(p->left)
            {
                q.push(p->left);
            }

            if(p->right)
            {
                q.push(p->right);
            }
            swap(p->left,p->right);
        }
        return root;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值