思路:
由先序找到根节点,即先序的第一个元素,
然后从中序中找到它的位置,以确定左右孩子,即它的左右两边的元素
依次递归
#include <stdio.h> #include <stdlib.h> #include <string.h> #define status int #define OK 1 #define ERROR 0 #define OVERFLOW -1 int k = 1; typedef struct Node{ char data; Node *left; Node *right; }*Tree; status Recover(Tree &T, char Pr[], char In[], int s, int e) { if(s > e) return ERROR; if(!T) { T = (Tree)malloc(sizeof(Node)); T->data = Pr[k++]; T->left = T->right = NULL; } int i; for(i = s; i <= e; i++) if(Pr[k-1] == In[i]) break; Recover(T->left, Pr, In, s, i-1); Recover(T->right, Pr, In, i+1, e); return OK; } status Ba(Tree T) { if(!T) return ERROR; Ba(T->left); Ba(T->right); printf("%c", T->data); return OK; } int main() { char Pr[27], In[27]; int m; while(scanf("%s %s", Pr+1, In+1) != EOF) { Tree T = NULL; m = strlen(Pr+1); Recover(T, Pr, In, 1, m); Ba(T); putchar(' '); k = 1; } return 1; }