操作给定的二叉树,将其变换为源二叉树的镜像。
递归解法:
/*
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==NULL) || ( pRoot->left == NULL && pRoot->right==NULL) )
return;
//交换左右节点
TreeNode *pTemp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = pTemp;
if( pRoot->left )
Mirror( pRoot->left );
if( pRoot->right )
Mirror( pRoot->right );
return;
}
};
非递归解法:
/*
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==NULL)
return;
stack<TreeNode*> stackNode;
stackNode.push(pRoot);
while(stackNode.size()){
TreeNode* tree=stackNode.top();
stackNode.pop();
if(tree->left!=NULL || tree->right!=NULL){
TreeNode *ptemp=tree->left;
tree->left=tree->right;
tree->right=ptemp;
}
if(tree->left)
stackNode.push(tree->left);
if(tree->right)
stackNode.push(tree->right);
}
}
};