由树的中序和先序遍历得到原来的树

来源:互联网 发布:数学建模优化模型 编辑:程序博客网 时间:2024/05/01 17:14

先序遍历的意义:任何一个节点的父节点都早于他遍历。

中序遍历的意义:任何一个节点都晚于左子树上的节点早于右子树上的节点被遍历。

in.txt   第一行是表示有多少个节点

61 2 3 4 5 62 1 5 4 3 6

程序:

获得原来的树放在tab表中 root 的左右孩子分别是 2*root 和 2*root +1 

#include<cstdio>#include<cmath>#include<iostream>#include<vector>using namespace std;int root=1;int a[20],_a[20],b[20],_b[20],tab[200];int getpos(int *tab,int v){int pos=1;while(tab[pos]!=v)pos++;return pos;}void build(int len){tab[len]=a[root];int pos=getpos(b,a[root]);_b[pos]=1;if(!_b[pos-1]){root++,build(len*2);}if(!_b[pos+1]){root++,build(len*2+1);}}void show_first(int root){if(!tab[root])return;cout<<tab[root]<<" ";show_first(root*2);show_first(root*2+1);}void show_mid(int root){if(!tab[root])return;show_mid(root*2);cout<<tab[root]<<" ";show_mid(root*2+1);}int main(){freopen("in.txt","r",stdin);int n;scanf("%d",&n);for(int i=0;i<n;i++)scanf("%d",&a[i+1]);for(int i=0;i<n;i++)scanf("%d",&b[i+1]);memset(_a,0,sizeof(_a));memset(_b,0,sizeof(_b));_b[0]=1;_b[n+1]=1;//边界build(1);cout<<""<<endl;show_first(1);cout<<endl;show_mid(1);cout<<endl;}


原创粉丝点击