您的位置:首页 > 其它

二叉树的还原与遍历

2014-04-07 16:38 155 查看
由前序遍历串与中序遍历串还原二叉树,并得到二叉树的后序遍历串。

#include<stdio.h>
#include<string.h>
struct Node{ //树结点结构体
Node *lchild;
Node *rchild;
char c;
}Tree[50];

int loc;//静态数组中已经分配的结点个数
Node *creat(){//申请一个结点空间,返回指向其的指针
Tree[loc].lchild = Tree[loc].rchild = NULL;
return &Tree[loc++];
}

void postOrder(Node * T){//后序遍历树
if(T->lchild != NULL)
postOrder(T->lchild );
if(T->rchild != NULL)
postOrder(T->rchild );
printf("%c",T->c );
}

char str1[30],str2[30];
Node *build(int s1,int e1,int s2,int e2)//由前序和中序遍历结果还原二叉树
{
Node *root = creat();
root->c = str1[s1];
int rootidx;
for(int i=s2;i<=e2;i++)
{
if(str1[s1]==str2[i])
{
rootidx = i;
break;
}
}

if(rootidx!=s2)//左子树不为空
{
root->lchild = build(s1+1,s1+(rootidx-s2),s2,rootidx-1);
}
if(rootidx!=e2)//右子树不为空
{
root->rchild = build(s1+(rootidx-s2)+1,e1,rootidx+1,e2);
}
return root;
}

int main()
{
while(scanf("%s",str1)!=EOF)
{
//        getchar();
scanf("%s",str2);
loc = 0;
int l1 = strlen(str1);
int l2 = strlen(str2);
Node *T = build(0,l1-1,0,l2-1);
postOrder(T);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: