您的位置:首页 > 其它

【前序中序求后序/后序中序求前序层次】【模板】

2016-05-17 01:46 295 查看
这是数据结构的知识。。。

刚开始先拒绝用指针去写。当我把这个想法和别人分享是,别人说不喜欢用指针的程序员不是一个好的c/c++程序员。。。

所以,就有了这么励志的时刻,我参考大牛的代码,自己用指针写了个遍,直接1A ...不用指针总是出现各种想不到的错误。。。心累。。。orz....

直接上代码,至于怎么求,过程是什么,我想百度上一大堆,就不多说了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<queue>
using namespace std;
typedef struct tree
{
tree *l,*r;
int num;
}tree;
tree *head;
// 已知a为前序,b为后序,建树;
tree *creat_postorder(int *a,int *b,int len)
{
tree *t;
for(int i=0;i<len;i++){
if(a[0]==b[i]){
t=(tree*)malloc(sizeof(tree)); // 申请一个指针;
t->num=b[i];
t->l=creat_postorder(a+1,b,i); // 左建树;
t->r=creat_postorder(a+i+1,b+i+1,len-i-1); // 右建树;
return t;
}
}
return NULL;
}
// 已知a为后序,b为中序;
tree *creat_preorder(int *a,int *b,int len)
{
tree *t;
for(int i=0;i<len;i++){
if(a[len-1]==b[i]){
t=(tree*)malloc(sizeof(tree));
t->num=b[i];
t->l=creat_preorder(a,b,i);
t->r=creat_preorder(a+i,b+i+1,len-i-1);
return t;
}
}
return NULL;
}
// 后序遍历;
void postorder(tree *h)
{
if(h!=NULL){
postorder(h->l);
postorder(h->r);
if(h==head)
cout<<h->num;
else
cout<<h->num<<' ';
}
}
// 前序遍历;
void preorder(tree *h)
{
if(h!=NULL){
if(h==head) cout<<h->num;
else cout<<' '<<h->num;
preorder(h->l);
preorder(h->r);
}
}
// 层次遍历
void levelorder(tree *h)
{
tree *temp;
queue<tree *>q;
q.push(h);
int flag=0;
while(!q.empty()){
temp=q.front();
if(flag) cout<<' '<<temp->num;
else cout<<temp->num;
flag=1;
q.pop();
if(temp->l)
q.push(temp->l);
if(temp->r)
q.push(temp->r);
}
}
int main()
{
int a[1010],b[1010];
int n;
cin.sync_with_stdio(false);
while(cin>>n){
head=NULL;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
cin>>b[i];
head=creat_postorder(a,b,n); // 知道前序中序建树;
postorder(head);
//head=creat_preorder(a,b,n); // 知道中序后序建树;
//preorder(head); // 求前序
//levelorder(head); // bfs求层次
cout<<endl;
}
return 0;
}
/*
前序中序求后序
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
7 4 2 8 9 5 6 3 1
后序中序求前序;
9
7 4 2 8 9 5 6 3 1
4 7 2 1 8 5 9 3 6
1 2 4 7 3 5 8 9 6
后序中序求层次
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
4 1 6 3 5 7 2
*/


题目1:告诉前序中序求后序,模板题 http://acm.hdu.edu.cn/showproblem.php?pid=1710
题目2:告诉中序后序求前序,模板题
https://www.patest.cn/contests/gplt/L2-006
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: