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

来源:互联网 发布:4g 高速网络 编辑:程序博客网 时间:2024/06/06 00:57
#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;
}
原创粉丝点击