题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
问题分析
BFS和DFS的套路,要么递归实现要么利用队列进行层序遍历。
- BFS 广度优先搜索法
- DFS 深度优先搜索法
BFS和DFS的理解
解题思路1
- 递归法
/*
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){
swap(pRoot->left, pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
}
}
};
解题思路2
- 层序遍历
/*
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;
}
//队列特点是先进先出
queue<TreeNode*> que;
que.push(pRoot);
TreeNode* tmp = NULL;
while(!que.empty())
{
//取出队头元素,并弹出
tmp = que.front();
que.pop();
swap(tmp->left,tmp->right);
if(tmp->left)
{
que.push(tmp->left);
}
if(tmp->right)
{
que.push(tmp->right);
}
}
}
};
网友评论