二叉树的镜像(十八)

题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:

源二叉树 
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

代码(已在牛客上 AC)

class Solution {
public:
void Mirror(TreeNode *pRoot) {
pRoot = setMirror(pRoot);
return;
}
private:
TreeNode* setMirror(TreeNode *root) {
if (!root) return nullptr;
std::swap(root->left, root->right);
root->left = setMirror(root->left);
root->right = setMirror(root->right);
return root;
}
};

C++ 实现 2

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

力扣上重做了一下, 还可以使用层序遍历实现:

class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if (!root) return nullptr;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
auto size = q.size();
while (size --) {
auto r = q.front();
q.pop();
if (r->left) q.push(r->left);
if (r->right) q.push(r->right);
std::swap(r->left, r->right);
}
}
return root;
}
};