一道建樹的標準題,先把遞歸把樹建起來,再用隊列輸出。一開始自己也忘得差不多了,也是學習了別人的代碼,要好好鞏固鞏固纔行。。。
#include<bits/stdc++.h>
using namespace std;
int post[50];
int in[50];
struct node{
int data;
node* left;
node* right;
};
node* BuildTree(int postL,int postR,int inL,int inR)
{
if(postL > postR)
return NULL;
int k;
for(k = inL;k<=inR;k++)
{
if(in[k] == post[postR])
break;
}
int num = k - inL;
node* root = new node;
root->data = post[postR];
root->left = BuildTree(postL,postL+num-1,inL,k-1);
root->right = BuildTree(postL+num,postR-1,k+1,inR);
return root;
}
main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&post[i]);
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
node* root = BuildTree(0,n-1,0,n-1);
queue<node*> q;
int cnt = 0;
q.push(root);
while(q.empty()==0)
{
node* temp = q.front();
q.pop();
if(cnt==0)
{
printf("%d",temp->data);
cnt++;
}
else
printf(" %d",temp->data);
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
return 0;
}