大致了解了一下。层次遍历的同时,用中序序列求出子树的下标范围,并标记在子树根结点上。利用左右孩子为空的特殊情况,一层一层构造,直至叶子结点。
代码如下,思路详见注释:
- #include<stdio.h>
- #include<iostream>
- #include<queue>
- using namespace std;
-
- typedef struct Bitree{
- char data;
- struct Bitree *lchild;
- struct Bitree *rchild;
- }Bitree,*Bi;
-
- typedef struct{
- int lel; //指向当前处理的元素在层次序列中的位置
- int low,high; //中序序列的上下界
- Bi parent; //层次序列中当前结点的双亲结点指针
- int lr; //判断左右子树,1为左,2为右
- }Sq;
-
- void preorder(Bi p);
-
- void Creat(Bi &bt,char lev[],char in[],int n)
- {
- Sq q;
- queue <Sq> Q;
- if(n<1)
- bt=NULL; //二叉树为空
- else
- {
- int i,s;
- i=s=0; //s指向层次序列中当前处理的元素,i用来寻找当前处理的元素在中序序列中的位置
- bt=new Bitree;
- bt->data=lev[0];
- bt->lchild=bt->rchild=NULL;
- while(in[i]!=lev[0])
- i++;
- if(i==0 && i==n-1) return ; //只有一个根节点
- if(i==0) //没有左子树
- {
- bt->lchild=NULL;
- q.lel=++s; q.low=i+1; q.high=n-1; q.lr=2; q.parent=bt;
- Q.push(q);
- }
- else if(i==n-1) //没有右子树
- {
- bt->rchild=NULL;
- q.lel=++s; q.low=0; q.high=i-1; q.lr=1; q.parent=bt;
- Q.push(q);
- }
- else
- {
- q.lel=++s; q.low=0; q.high=i-1; q.lr=1; q.parent=bt;
- Q.push(q);
- q.lel=++s; q.low=i+1; q.high=n-1; q.lr=2; q.parent=bt;
- Q.push(q);
- }
- while(!Q.empty())
- {
- q=Q.front(); Q.pop();
- Bi fat=q.parent;
- i=q.low;
- while(in[i]!=lev[q.lel])
- i++;
- Bi p=new Bitree;
- p->data=lev[q.lel];
- p->lchild=p->rchild=NULL;
- if(q.lr==1)
- fat->lchild=p;
- else
- fat->rchild=p;
- if(i==q.low && i==q.high) //叶子结点,无孩子
- {
- p->lchild=p->rchild=NULL;
- continue;
- }
- else if(i==q.low) //没有左孩子
- {
- p->lchild=NULL;
- q.lel=++s; q.low=i+1; q.parent=p; q.lr=2;
- Q.push(q);
- }
- else if(i==q.high) //没有右孩子
- {
- p->rchild=NULL;
- q.lel=++s; q.high=i-1; q.parent=p; q.lr=1;
- Q.push(q);
- }
- else
- {
- int high=q.high; //备份一下
- q.lel=++s; q.high=i-1; q.parent=p; q.lr=1;
- Q.push(q);
- q.lel=++s; q.low=i+1; q.high=high; q.parent=p; q.lr=2;
- Q.push(q);
- }
- }
- }
- }
-
- int main()
- {
- int n;
- Bitree *B;
- char in[50],lev[50];
- printf("请输入结点个数\n");
- cin>>n;
- printf("请输入中序遍历和层次遍历\n");
- getchar();
- gets(in); gets(lev);
- Creat(B,lev,in,n);
- printf("构造完成,输出先序序列\n");
- preorder(B);
- return 0;
- }
- void preorder(Bi p)
- {
- if(p)
- {
- printf("%c ",p->data);
- preorder(p->lchild);
- preorder(p->rchild);
- }
- }