题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述

1
2
3
4
5
6
7
二叉树的镜像定义:
源二叉树 镜像二叉树
8 8
/ \ / \
6 10 10 6
/ \ / \ / \ / \
5 7 9 11 11 9 7 5

接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {

}
};

解答

递归方法

对于每个二叉树结点都将左右子结点交换就可以,因此递归是最简短的形式,可以先继续递归左右子结点再交换左右子结点,也可以先交换左右子结点再继续递归左右子结点。

继续递归左右子结点时,可以先检查左右子结点是否为 nullptr,如果子结点是 nullptr,则不需要进行递归,可以减少内存空间和运行时间的消耗,因为递归需要为递归函数的参数和局部变量分配内存空间,同时还需要对递归函数进行压栈操作和递归函数执行及执行完后的出栈操作,这些都需要消耗时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if (pRoot == nullptr) return;
if (pRoot->left != nullptr) Mirror(pRoot->left);
if (pRoot->right != nullptr) Mirror(pRoot->right);
TreeNode* temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
}
};

stl::queue 非递归方法

通过队列以层次遍历的方式,遍历每一个二叉树结点,取出结点将左右子结点交换,再将非 nullptr 的子结点加入队列中,直到队列为空。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if (pRoot == nullptr) return;
queue<TreeNode*> que;
que.push(pRoot);
TreeNode *node = nullptr, *temp = nullptr;
while (que.empty() == false) {
node = que.front();
que.pop();
temp = node->left;
node->left = node->right;
node->right = temp;
if (node->left != nullptr) que.push(node->left);
if (node->right != nullptr) que.push(node->right);
}
}
};

stl::stack 非递归方法

与 stl::queue 的思路相似,故不再叙述。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if (pRoot == nullptr) return;
stack<TreeNode*> stk;
stk.push(pRoot);
TreeNode *node = nullptr, *temp = nullptr;
while (stk.empty() == false) {
node = stk.top();
stk.pop();
temp = node->left;
node->left = node->right;
node->right = temp;
if (node->left != nullptr) stk.push(node->left);
if (node->right != nullptr) stk.push(node->right);
}
}
};