这两题都是给出两个序列求另一个序列
A1020
A1020非常直接,就是根据后序遍历和中序遍历重建二叉树,然后层序遍历输出
#include<bits/stdc++.h>
using namespace std;
const int maxn=35;
typedef struct Node* TNode;
struct Node
{
int data;
TNode left,right;
};
int post[maxn],in[maxn],n;
TNode create(int postL,int postR,int inL,int inR)
{
if(postL>postR) return NULL;
TNode root=(TNode)malloc(sizeof(struct Node));
root->data=post[postR];
int leftNum=0;int mid=0;
for(int i=inL;i<=inR;i++)
{
if(in[i]==post[postR])
{
mid=i;
break;
}
}
leftNum=mid-inL;
root->right=create(postL+leftNum,postR-1,mid+1,inR);
root->left=create(postL,postL+leftNum-1,inL,mid-1);
return root;
}
void BFS(TNode root)
{
queue<TNode> q;
q.push(root);
TNode top;
int num=0;
while(!q.empty())
{
top=q.front();
q.pop();num++;
printf("%d",top->data);
if(num!=n) printf(" ");
if(top->left!=NULL) q.push(top->left);
if(top->right!=NULL) q.push(top->right);
}
}
int main()
{
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]);
}
TNode root=create(0,n-1,0,n-1);
BFS(root);
}
A1086
A1086则用栈的思想“修饰”了一下题目
本质上还是用先序序列和中序序列重建树,然后后序遍历输出
push的过程也就是先序遍历的过程,每次把根结点先push进去
pop的序列是中序序列,先pop左结点,再中,再右.
其他注意点:在后序遍历递归输出时,计数的变量必须是全局变量。
而上一题层序遍历没有用到递归,所以计数变量是全局还是局部就无关紧要了。
#include<bits/stdc++.h>
using namespace std;
const int maxn=35;
typedef struct Node* TNode;
struct Node
{
int data;
TNode left,right;
};
int n;
int pre[maxn],in[maxn],post[maxn];
TNode create(int preL,int preR,int inL,int inR)
{
if(preL>preR) return NULL;
TNode root=(TNode)malloc(sizeof(struct Node));
root->data=pre[preL];
int mid=0;
for(int i=inL;i<=inR;i++)
{
if(in[i]==pre[preL])
{
mid=i;
break;
}
}
int leftNum=mid-inL;
root->left=create(preL+1,leftNum+preL,inL,mid-1);
root->right=create(preL+leftNum+1,preR,mid+1,inR);
return root;
}
int num=0;
void postTraversal(TNode root)
{
if(root==NULL) return;
if(root!=NULL)
{
postTraversal(root->left);
postTraversal(root->right);
printf("%d",root->data);
num++;
if(num!=n) printf(" ");
}
}
int main()
{
scanf("%d",&n);
stack<int> s;
char str[10];
int t,num1=0,num2=0;
for(int i=0;i<n*2;i++)
{
scanf("%s",str);
if(strcmp(str,"Push")==0)
{
scanf("%d",&t);
pre[num1++]=t;
s.push(t);
}
else if(strcmp(str,"Pop")==0)
{
in[num2++]=s.top();
s.pop();
}
}
TNode root=create(0,n-1,0,n-1);
postTraversal(root);
}