PTA 6-9 确定二叉树(先序序列+中序序列)分数 10 作者 黄龙军 单位 绍兴文理学院

要求实现函数,根据二叉树的先序序列和中序序列确定二叉树并返回指向二叉树根结点的指针。二叉树采用二叉链表存储,结点结构如下:

struct BiTNode {                                  // 结点结构 
    int data;                                     // 数据域 
    BiTNode *lchild,*rchild;                      // 左右孩子指针 
    BiTNode(int d,BiTNode *left,BiTNode *right) { // 构造函数 
        data=d;
        lchild=left;
        rchild=right;
    }
};

函数接口定义:

BiTNode* CreateBT(int* pre, int *in, int n);

其中参数 pre是指向先序序列数组首元素的指针, in是指向中序序列数组首元素的指针 ,n是结点总数。

裁判测试程序样例:

#include<iostream>
using namespace std;

struct BiTNode {                                  // 结点结构 
    int data;                                     // 数据域 
    BiTNode* lchild, * rchild;                      // 左右孩子指针 
    BiTNode(int d, BiTNode* left, BiTNode* right) { // 构造函数 
        data = d;
        lchild = left;
        rchild = right;
    }
};

void PostOrder(BiTNode* p, int& cnt)    // 后序遍历
//  根据先序序列和中序序列确定二叉树,pre是指向后序序列数组首元素的指针,in是指向中序序列数组首元素的指针 ,n是结点总数
BiTNode* CreateBT(int* pre, int* in, int n);

// 根据先序序列和中序序列创建二叉树并后序遍历之
int main() {
    int n;
    while (cin >> n) {
        int pre[n], in[n], cnt = 0;
        for (int i = 0; i < n; i++) cin >> pre[i];
        for (int i = 0; i < n; i++) cin >> in[i];
        BiTNode* root = CreateBT(pre, in, n);
        PostOrder(root, cnt);
        cout << endl;
    }
    return 0;
}
//下面是你的代码

输入样例:

9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6

输出样例:

7 4 2 8 9 5 6 3 1

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

答案:

BiTNode* creaate_bt(int* pre, int* in,int& index, int start, int end) {

    if (start > end) {
        return NULL;
    }
    int root = pre[index];
    int i = 0;
    for (i = start; i <= end; i++) {
        if (in[i] == root) break;
    }
    BiTNode* new_node = (BiTNode*)malloc(sizeof(BiTNode));
    new_node->data = pre[index++];
    new_node->lchild= creaate_bt(pre, in, index, start, i - 1);
    new_node->rchild= creaate_bt(pre, in, index, i + 1, end);
    //index为引用,这个递归过程为递增的,对标先序从前到后,用于取pre的值。index与pre并无直接关系,因此递归并不能将i+1作为右子树递归的index
    return new_node;
}

BiTNode* CreateBT(int* pre, int* in, int n) {
    
    int index = 0;
    return  creaate_bt(pre, in,index ,0, n - 1);//index为pre的当前所取根元素(根左右),后两个为in的起止区间。

}

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值