2016计算机学科夏令营上机考试G:重建二叉树(二叉树重建+遍历)

在这里插入图片描述

思路分析

本题非常非常典型!
已知前序遍历+中序遍历,可以得到后序遍历;
已知后序遍历+中序遍历,可以得到前序遍历。
因为前序遍历的第一个结点为根节点,中序遍历以该根节点为界,分为左右子树,不断递归每个子树即可将二叉树重建出来,之后再对其进行后序遍历即可。所以每次的任务便是在中序遍历中找到根节点,并确定每个子树的左、右边界

node* Change(int pre_L, int pre_R, int in_L, int in_R)
eg1. 先序遍历+中序遍历

在这里插入图片描述

int num_left = k - in_L; // 左子树结点的个数
root -> lchild = Change(pre_L+1, pre_L+num_left, in_L, k-1); // 左子树
root -> rchild = Change(pre_L+num_left+1, pre_R, k+1, in_R); // 右子树
eg2. 后续遍历+中序遍历

在这里插入图片描述

int num_left = k - in_L; // 左子树结点的个数
root -> lchild = Change(post_L, post_L+num_left-1, in_L, k-1); // 左子树
root -> rchild = Change(post_L+num_left, post_R-1, k+1, in_R); // 右子树

代码

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

const int maxn = 1010;
char pre[maxn], in[maxn], post[maxn];

struct node
{
    char data;
    node* lchild;
    node* rchild;
};

node* Change(int pre_L, int pre_R, int in_L, int in_R)
{
    if(pre_L > pre_R) // 边界条件
    {
        return NULL;
    }
    node* root = new node;
    root -> data = pre[pre_L]; // 根结点
    int k; // 中序数组中根结点的下标
    for(k=in_L; k<=in_R; k++)
    {
        if(in[k] == pre[pre_L])
        {
            break;
        }
    }
    int num_left = k - in_L; // 左子树结点的个数
    root -> lchild = Change(pre_L+1, pre_L+num_left, in_L, k-1); // 左子树
    root -> rchild = Change(pre_L+num_left+1, pre_R, k+1, in_R); // 右子树

    return root;
}

void postorder(node* root) // 后序遍历
{
    if(root == NULL)
    {
        return ;
    }
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%c", root->data);
}

int main()
{
    freopen("input.txt", "r", stdin);
    while(scanf("%s %s", pre, in) != EOF)
    {
        int len_pre = strlen(pre);
        int len_in = strlen(in);
        node* tree = Change(0, len_pre-1, 0, len_in-1);
        postorder(tree);
        printf("\n");
    }
    fclose(stdin);

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值