由中序遍历可知一个结点左右孩子是哪几个结点,由前序遍历可知根节点的位置。
由此信息可以得知,先用strchr函数找出前序遍历第一个根节点在中序遍历的位置,并存储在pos中。
当pos>0明显可知,左子树不为空,此时递归求下一个根节点,
此时pre_str = pre_str+1, in_str = in_str,len =pos。
当len-pos-1>0时明显可知,右子树不为空,此时递归求下一个根节点,
此时pre_str = pre_str+pos+1, in_str = in_str+pos+1,len = len-pos-1
而求反转,只需将上述操作左右孩子对换,便可求得。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int maxn = 50;
typedef struct Node{
int data;
struct Node *lchild, *rchild;
}Node;
Node* init(int data){
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
void postorder(Node *node){
if (node->lchild != NULL){
postorder(node->lchild);
}
if (node->rchild != NULL){
postorder(node->rchild);
}
printf("%c", node->data);
}
Node* build(char pre_str[], char in_str[], int len){
Node* p = init(pre_str[0]);
int pos = strchr(in_str, pre_str[0]) - in_str;
if (pos>0){
p->lchild = build(pre_str + 1, in_str, pos);
}
if (len - pos - 1>0){
p->rchild = build(pre_str + pos + 1, in_str + pos + 1, len - pos - 1);
}
return p;
}
Node *reverse(char pre_str[], char in_str[], int len){
Node *p = init(pre_str[0]);
int pos = strchr(in_str, pre_str[0]) - in_str;
if (pos>0){
p->rchild = reverse(pre_str + 1, in_str, pos);
}
if (len - pos - 1>0){
p->lchild = reverse(pre_str + pos + 1, in_str + pos + 1, len - pos - 1);
}
return p;
}
void clear(Node *node){
if (node->lchild != NULL){
clear(node->lchild);
}
if (node->rchild != NULL){
clear(node->rchild);
}
free(node);
}
int main(){
char pre_str[maxn];
char in_str[maxn];
memset(pre_str, '\0', maxn);
memset(in_str, '\0', maxn);
scanf("%s", pre_str);
scanf("%s", in_str);
Node *root = build(pre_str, in_str, strlen(pre_str));
Node *root2 = reverse(pre_str, in_str, strlen(pre_str));
postorder(root);
printf("\n");
postorder(root2);
clear(root);
clear(root2);
return 0;
}