CODE[VS]1013 求先序排列

题目: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值