标题: | 由二叉树的中序层序重建二叉树 | |
时 限: | 1000 ms | |
内存限制: | 10000 K | |
总时限: | 3000 ms | |
描述: |
给定一棵二叉树的中序和层序输出,生成这棵树并按先序和后序输出
其中树结构中结点信息为整数 | |
输入: |
| |
输出: |
先序遍历
后序遍历 | |
输入样例: |
1 2 3 5 6 7
2 5 1 6 3 7 | |
输出样例: |
1 2 5 3 6 7
5 2 6 7 3 1 |
//编译环境G++
#include <stdio.h>
#include <stdlib.h>
//TreeNode///
typedef struct _TreeNode
{
//char key;
int key;
struct _TreeNode *Lc;
struct _TreeNode *Rc;
}TreeNode;
Queue//
//队列节点的元素类型
typedef struct _QElement
{
int lvl;//指向当前根节点在层次序列中的位置
int l,h;//中序序列的上、下界
TreeNode *f;//层次序列中当前根节点的双亲节点指针
int lr;// 指示符,0:根结点,1:双亲的左子树,2:双亲的右子树
}QElement;
//队列节点
typedef struct _QNode
{
QElement data;
struct _QNode *next;
}QNode;
//队列
typedef struct _Queue
{
QNode *front;
QNode *rear;
}Queue;
void InitQueue(Queue &Q)
{
Q.front=Q.rear=(QNode*)malloc(sizeof(QNode));
if(!Q.front) exit(0);
Q.front->next=NULL;
//Q.front->next=Q.rear->next=NULL;
//Q.front=NULL;
//Q.rear=NULL;
}
bool isemptyQ(Queue &Q)
{
//if(Q.front==NULL)
if(Q.front==Q.rear)
return 1;
return 0;
}
void EnQueue(Queue &Q,QElement e)
{
QNode *p;
p=(QNode*)malloc(sizeof(QNode));
if(!p) exit(0);
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}
void DeQueue(Queue &Q,QElement &e)
{
QNode* p;
if(Q.front==Q.rear)
exit(0);
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p)
Q.rear=Q.front;
free(p);
}
int RepreOrder(TreeNode *T)
{
//TreeNode *p=T;
if(T)
{
printf("%d ",T->key);
RepreOrder(T->Lc);
RepreOrder(T->Rc);
}
return 0;
}
int RePostOrder(TreeNode *T)
{
if(T)
{
RePostOrder(T->Lc);
RePostOrder(T->Rc);
printf("%d ",T->key);
}
return 0;
}
//参考了http://www.cnblogs.com/xiaofengkang/archive/2011/05/22/2053493.html
TreeNode* CreatFromLevelIn(int *level,int *in, int n)
{
int r=-1,low,high,lr,i,j;
TreeNode *root=NULL,*p,*father;
int ch;
QElement s;
Queue Q;
InitQueue(Q);
s.lvl=level[++r];
s.l=0;
s.h=n-1;
s.f=NULL;
s.lr=0;
EnQueue(Q,s);
while(!isemptyQ(Q))
{
DeQueue(Q,s);
ch=s.lvl;
low=s.l;
high=s.h;
father=s.f;
lr=s.lr;
for(j=low;j<=high;j++)
{
if(in[j]==ch)
{
i=j;
//printf("i=%d\n",i);//system("pause");
break;
}
}//for
p=(TreeNode*)malloc(sizeof(TreeNode));
p->key=ch;
p->Lc=p->Rc=NULL;
if(lr==0) root=p;
else if(lr==1) father->Lc=p;
else father->Rc=p;
if(low==high) continue;//跳出本次for循环
if(i==low)//无左子树
{
s.l=low+1;
s.lr=2;
s.lvl=level[++r];
s.f=p;
EnQueue(Q,s);
}
else if(i==high)//无右子树
{
s.h=high-1;
s.lr=1;
s.lvl=level[++r];
s.f=p;
EnQueue(Q,s);
}
else
{
s.h=i-1;
s.l=low;
s.lr=1;
s.lvl=level[++r];
s.f=p;
EnQueue(Q,s);
s.l=i+1;
s.h=high;
s.lr=2;
s.lvl=level[++r];
s.f=p;
EnQueue(Q,s);
}//else
}//while
return root;
}//CreatFromLevelIn
int main()
{
int len;
scanf("%d",&len);
int *level=(int*)malloc(sizeof(int)*len);
int *in=(int*)malloc(sizeof(int)*len);
int i;
for(i=0;i<len;i++)
{
scanf("%d",level+i);
}
for(i=0;i<len;i++)
{
scanf("%d",in+i);
}
TreeNode *newnode=(TreeNode*)malloc(sizeof(TreeNode));
newnode=CreatFromLevelIn(level,in,len);
RepreOrder(newnode);
printf("\n");
RePostOrder(newnode);
return 0;
}