知道二叉树的中序遍历和一种遍历后,可以求另一种遍历。
(1)先序遍历的第一个元素是后序的最后一个
(2)可以用先(后)序遍历把中序遍历分开,递归创二叉树
/**/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node * BT;
#define N
struct node
{
char str;
BT left;
BT right;
};
BT creat(int len,char pre[],char mid[])
{
int i;
BT root=(BT)malloc(sizeof(struct node));
root->str=pre[0];
for(i=0;i<len;i++)
{
if(mid[i]==pre[0])
{
break;
}
}
if(i>=len)
root=NULL;
else
{
root->left=creat(i,pre+1,mid);
root->right=creat(len-1-i,pre+1+i,mid+1+i);
}
return root;
}
void bac(BT root)
{
if(root)
{
bac(root->left);
bac(root->right);
printf("%c",root->str);
}
}
int main()
{
char pre[55],mid[55];
int len;
BT tree;
scanf("%s %s",pre,mid);
len=strlen(pre);
tree=creat(len,pre,mid);
bac(tree);
printf("\n");
return 0;
}