PAT甲级1020 Tree Traversals (25 分)思路
- 题意:给出一个二叉树的后序遍历和中序遍历,要求输出其层次遍历。
- 思路:需要用到递归的方式根据后序遍历和中序遍历的情况得到根结点和左子树及右子树,再把得到的左子树和右子树分别进行相同的递归求解,最后得到完整的二叉树,再用BFS层次遍历二叉树得到其层次遍历的结果。
- step1:创建node结点,其中左子树和右子树的类型为node*,表示node型变量的地址。
- step2:定义递归函数,根据中序后序遍历的情况递归的构建出二叉树:具体为node* create(int postL,int postR,int inL,int inR)、当前二叉树的后序序列区间为[postL,postR],中序序列区间为[inL,inR],递归结束条件是后序遍历的左结点位置大于右结点位置,首先创建node*型的结点地址,将其指向的数据赋值为当前后序遍历的最后一个数(即为根),在中序中找根,标记根的下标,由此得出左子树和右子树的元素个数,接下去在进行递归调用,最后返回根。
- step3:定义BFS函数层次遍历二叉树输出即可。
因为是大二时候学的数据结构了,现在按照《算法笔记》上的代码整理了一下自己的思路,字数有些多了,但思路清晰,代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn=50;
struct node
{
int data;
node* lchild;
node* rchild;
};
int pre[maxn],in[maxn],post[maxn];
int n;
node* create(int postL,int postR,int inL,int inR)
{
if(postL>postR)
{
return NULL;
}
node* root=new node;
root->data=post[postR];
int k;
for(k=inL;k<=inR;k++)
{
if(in[k]==post[postR])break;
}
int numLeft=k-inL;
root->lchild=create(postL,postL+numLeft-1,inL,k-1);
root->rchild=create(postL+numLeft,postR-1,k+1,inR);
return root;
}
int num=0;
void BFS(node* root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* now=q.front();
q.pop();
printf("%d",now->data);
num++;
if(num<n)printf(" ");
if(now->lchild!=NULL)q.push(now->lchild);
if(now->rchild!=NULL)q.push(now->rchild);
}
}
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]);
}
node* root=create(0,n-1,0,n-1);
BFS(root);
return 0;
}