1,题目要求
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:
源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
2,题目思路
对于这道题,要求将一棵二叉树变为镜像二叉树。
所谓镜像二叉树,就是所有节点从上到下,依次左右互换。
因此,我们只需要递归地遍历这棵树,然后利用swap函数交换每个节点的左右孩子节点即可。
3,代码实现
/*
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)
return;
swap(pRoot->left, pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
return;
}
};