话说偶一直找不到广义表的用武之地,今天书上一个例题很好将广义表跟二叉树结合到了一起,其实二叉树不就是一个深层的广义表么。怪不得把广义表放在树前边讲。放码子: #include<iostream> using namespace std; const int nax=100; typedef struct tr { int data,left,right; int label; }btree; btree tree[100]; bool ck[100]; int recreat(int *mid,int *post,int len)//len结点个数 { int i,j,root=0,troot;//troot是暂时根节点 for(i=0;i<len;i++) { tree[i].data=mid[i]; tree[i].left=tree[i].right=-1; tree[i].label=i; } while(post[len-1]!=tree[root].data)//寻找根节点在中序遍历数组中的位置 root++; /*从后序节点的倒数第二个开始扫描,依次与中序遍历的节点比较,找到其中序数组中的位置时, 用j记录下来,然后比较他的label值与根节点的label值,看看是左孙子,还是右孙子*/ for(i=len-2;i>=0;i--) { troot=root; j=0; while(post[i]!=tree[j].data)j++; while(troot!=-1) { if(tree[j].label<tree[troot].label)//插在左侧 { if(tree[troot].left==-1) { tree[troot].left=j; troot=-1; } else troot=tree[troot].left; } else if(tree[j].label>tree[troot].label) { if(tree[troot].right==-1) { tree[troot].right=j; troot=-1; } else troot=tree[troot].right; } } } return root; } void displaya(int root)//按照中序左根右的顺序输出,递归的详细版 { if (tree[root].left!=-1 && tree[root].right!=-1) { displaya(tree[root].left); printf("%d ",tree[root].data); displaya(tree[root].right); } else if (tree[root].left==-1 && tree[root].right!=-1) { printf("%d ",tree[root].data); displaya(tree[root].right); } else if (tree[root].right==-1 && tree[root].left!=-1) { displaya(tree[root].left); printf("%d ",tree[root].data); } else printf("%d ",tree[root].data); } void displayb(int root)//先序根左右 { if(root!=-1) { printf("%d ",tree[root].data); displayb(tree[root].left); displayb(tree[root].right); } } int main() { int i,n,mid[nax],post[nax]; memset(ck,0,sizeof(ck)); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&mid[i]); for(i=0;i<n;i++) scanf("%d",&post[i]); //display(recreat(mid,post,n)); displayb(recreat(mid,post,n)); return false; } ps:验证用的输出函数突然不会写,然后dreamfox相帮,算他一份功劳~~