#include <iostream>
using namespace std;
template <class elemType>
class linkQueue{
private:
struct node{
elemType data;
node *next;
node(const elemType &x,node *p=NULL){data=x; next=p;}
node():next(NULL){}
~node(){}
};
node *Front,*rear;
public:
linkQueue(){Front=rear=NULL;}
~linkQueue();
void enQueue(const elemType &x);
elemType deQueue();
bool isEmpty(){return (Front==NULL);}
elemType getHead(){return Front->data;}
};
template <class elemType>
linkQueue<elemType>::~linkQueue(){
node *q=Front,*p;
while(q!=NULL){
p=q->next;
delete q;
q=p;
}
}
template <class elemType>
void linkQueue<elemType>::enQueue(const elemType &x){
node *tmp;
if (Front==NULL) {
tmp=new node(x);
rear=Front=tmp;
}
else{
tmp=new node(x);
rear->next=tmp;
rear=tmp;
}
}
template <class elemType>
elemType linkQueue<elemType>::deQueue(){
node *tmp;
elemType value=Front->data;
tmp=Front;
Front=Front->next;
if (Front==NULL) rear=NULL;
delete tmp;
return value;
}
class seqBinaryTree{
private:
int *ltree,*rtree,*tree;
int currentSize,maxSize1,maxSize2;
void doubleSpace(int *&p,int &maxSize);
void post(int i);
public:
seqBinaryTree(){ltree=new int[30000]{0}; rtree=new int[30000]{0}; tree=new int[30000]{0}; maxSize1=maxSize2=30000; currentSize=0;}
~seqBinaryTree(){delete [] ltree; delete [] rtree; delete [] tree;}
void createTree(int n);
void post();
void show(int n);
};
void seqBinaryTree::post(){
post(1);
}
void seqBinaryTree::post(int i){
if (i==-1) return;
post(ltree[i-1]);
post(rtree[i-1]);
cout<<i<<' ';
}
void seqBinaryTree::doubleSpace(int *&q,int &n){
int *p=new int[n*2]{0};
for (int i=0;i<n;i++)
p[i]=q[i];
delete [] q;
q=p;
n=n*2;
}
void seqBinaryTree::createTree(int n){
while(n>maxSize1) {doubleSpace(ltree,maxSize1); doubleSpace(rtree,maxSize1);}
int index,ct=0,tmp,j=0;
linkQueue<int> que;
for (int i=0;i<n;i++){
cin>>index;
cin>>ltree[index-1];
cin>>rtree[index-1];
}
que.enQueue(1);
while(ct<n){
tmp=que.deQueue();
if (j>=maxSize2-1) doubleSpace(tree,maxSize2);
tree[j]=tmp;
j++;
if (tmp==-1){que.enQueue(-1);que.enQueue(-1);}
else {ct++; que.enQueue(ltree[tmp-1]); que.enQueue(rtree[tmp-1]);}
}
currentSize=j;
}
void seqBinaryTree::show(int n){
int *judge=new int[n]{0};
for (int i=0;i<currentSize;i++)
if (tree[i]!=-1)
judge[tree[i]-1]=i+1;
for (int j=0;j<n;j++)
cout<<judge[j]<<' ';
}
int main()
{
seqBinaryTree tree;
int n;
cin>>n;
tree.createTree(n);
tree.show(n);
cout<<endl;
tree.post();
return 0;
}
SJTU OJ (1039)
最新推荐文章于 2023-12-02 09:05:22 发布