二叉树镜像之递归、栈、队列实现

#include<iostream>
#include<stack>
#include<deque>
#define N 10
using namespace std;


struct BTnode{
int value;
BTnode* left;
BTnode* right;
};
BTnode *mirror(BTnode *root){
if(!root)
return NULL;
BTnode *tempLeft=root->left;
root->left=root->right;
root->right=tempLeft;
if(root->left)
mirror(root->left);
if(root->right)
mirror(root->right);
return root;
}
BTnode *mirror_stack(BTnode* root){
if(!root)
return NULL;
stack<BTnode *>sta;
sta.push(root);
while(sta.size()){
BTnode *temp=sta.top();
sta.pop();
BTnode* tempLeft=temp->left;
temp->left=temp->right;
temp->right=tempLeft;
if(temp->left)
sta.push(temp->left);
if(temp->right)
sta.push(temp->right);
}
return root;
}
BTnode *mirror_deque(BTnode* root){
if(!root)
return NULL;
deque<BTnode *>deq;
deq.push_back(root);
while(deq.size()){
BTnode *temp=deq.front();
deq.pop_front();
BTnode* tempLeft=temp->left;
temp->left=temp->right;
temp->right=tempLeft;
if(temp->left)
deq.push_back(temp->left);
if(temp->right)
deq.push_back(temp->left);
}
return root;
}
void LDRshowBT(BTnode* root){
cout<<root->value<<" ";
if(root->left)
LDRshowBT(root->left);
if(root->right)
LDRshowBT(root->right);
}
int main(){
BTnode *arr[N+1];
for(int i=1;i<=N;i++){
arr[i]=(BTnode*)malloc(sizeof(BTnode));
arr[i]->value=i;
arr[i]->left=NULL;
arr[i]->right=NULL;
}
for(int i=1;i<=N/2;i++){
arr[i]->left=arr[2*i];
if(2*i+1<=N)
arr[i]->right=arr[2*i+1];
}
LDRshowBT(arr[1]);
cout<<endl;
LDRshowBT(mirror_deque(arr[1]));
cout<<endl;
LDRshowBT(mirror_stack(arr[1]));
cout<<endl;
LDRshowBT(mirror(arr[1]));
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值