题目:http://codevs.cn/problem/1013/
思路:前序遍历:根->左->右,中序遍历:左->根->右,后序遍历:左->右->根。所以后序遍历最后的节点为根,由根节点可将中序遍历划分为两部分:左部和右部。根据左右分割位置,可得出左子树根节点和右子树根节点。
题解:
/* 1013 求先序排列 */
#include <stdio.h>
#define DEBUG
#define MAXL 9
/* 前序,中序,后序遍历数组 */
char preorder[MAXL], inorder[MAXL], postorder[MAXL];
int length; /* 根节点个数 */
/* 获取子树 */
void get_children(int s1, int e1, int s2, int e2){
int i , j;
/* 索引值超出范围 */
if(s1 >= e1 || s2 >= e2){
return;
}
/* 从中序遍历中查找根节点位置 */
for(i = s1; i <= e1; i++){
if(inorder[i] == postorder[e2]){
break;
}
}
/* 左,右子树分割点 */
j = i - s1;
/* 如果左子树节点大于0,打印左子树根节点,并查找其子树 */
if(j > 0){
printf("%c", postorder[s2 + j - 1]);
get_children(s1, i - 1, s2 , s2 + j - 1);
}
/* 如果右子树节点数大于0,打印右子树根节点,并查找其子树 */
if(j < e2 - s2){
printf("%c", postorder[e2 - 1]);
get_children(i + 1, e1, s2 + j, e2 - 1);
}
}
/* 主函数入口 */
int main(int argc, char *argv[]) {
#ifdef DEBUG
FILE *fp;
if(NULL == (fp = fopen("data.txt", "r"))){
return 1;
}
#endif
/* 获取中序,后序字符串 */
#ifdef DEBUG
fscanf(fp, "%s", inorder);
fscanf(fp, "%s", postorder);
#else
scanf("%s", inorder);
scanf("%s", postorder);
#endif
/* 获取长度 */
length = 0;
while(inorder[length] != '\0'){
length++;
}
printf("%c", postorder[length - 1]);
get_children(0, length - 1, 0, length - 1);
#ifdef DEBUG
fclose(fp);
#endif
return 0;
}