题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
方法一:使用递归方法
/*
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){
Mirror(pRoot->right);
Mirror(pRoot->left);
swap(pRoot->right, pRoot->left);
}
}
};
方法二:利用栈或队列来实现(一个是深度遍历交换,一个是广度遍历交换)
一下给出栈的版本(直接替换队列和队列函数即可,变成队列版本)
/*
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 ;
stack<TreeNode*> treeNodeStack;
treeNodeStack.push(pRoot);
while(!treeNodeStack.empty()){
TreeNode* currentNode = treeNodeStack.top();
treeNodeStack.pop();
if(currentNode->left || currentNode->right)
swap(currentNode->left, currentNode->right);
if(currentNode->left)
treeNodeStack.push(currentNode->left);
if(currentNode->right)
treeNodeStack.push(currentNode->right);
}
}
};