二叉树重建

给定二叉树的先序遍历序列和中序遍历序列,进行二叉树的重建以及后序遍历队列。
突然看到这个问题。。发现之前的想法都忘记了=_=||,果然算法题一日不写手生啊,还是得好好坚持练习才行啊。

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;

struct node{
    char ch;
    node *left;
    node *right;
};
char pre[100];
char in[100];

node *rec(int s1, int e1, int s2, int e2){
    node *tree = new node;
    char ch = pre[s1];
    tree->ch = ch;
    tree->left = NULL;
    tree->right = NULL;
    int rootidx;       //找到每一颗子树的根节点 划分左右子树
    for(int i=s2; i<=e2; i++){
        if(in[i] == ch){
            rootidx = i;
            break;
        }
    }
    if(rootidx != s2)        // 有左子树的话 那么这个字符在中序序列中肯定不是最左边的
        tree->left = rec(s1+1, s1+(rootidx-s2), s2, rootidx-1);
    if(rootidx != e2)
        tree->right = rec(s1+(rootidx-s2)+1, e1, rootidx+1, e2);
    return tree;

}

void postOrder(node *t){
    if(t){
        if(t->left)
            postOrder(t->left);
        if(t->right)
            postOrder(t->right);
        printf("%c", t->ch);
    }
}
int main(){
    while(~scanf("%s", pre)){
        scanf("%s", in);
        int l = strlen(pre);
        node *tree;
        tree = rec(0, l-1, 0, l-1);
        postOrder(tree);
        printf("\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值