intlongint 2021-09-18 19:31 采纳率: 50%
浏览 30
已结题

PAT 甲级1099 构建二叉树形状时使用递归出现段错误


#include<iostream>
using namespace std;
struct Tree
{
    int data;
    Tree* nl;
    Tree* nr;
};
struct Record
{
    int left;
    int right;
};
int i, j;
int N;
Record* obj = new Record[N];
int* node = new int[N];
int times = 0;
void build(Tree* nroot, int index)
{
    if (obj[index].left == -1) { nroot->nl = NULL;  }
    else { nroot->nl = new Tree; build(nroot->nl, obj[index].left); }
    if (obj[index].right == -1) { nroot->nr = NULL;  }
    else { nroot->nr = new Tree; build(nroot->nr, obj[index].right); }
    return;
}//出错的函数,但是visual studio 上又能够成功构造
void through(Tree*nroot)
{
    if (nroot == NULL) return;
    else
    {
    through(nroot->nl);
    nroot->data = node[times];
    ++times;
    through(nroot->nr);
    }
}
int main()
{
    cin >> N;
    for (i = 0; i < N; ++i)
        cin >> obj[i].left >> obj[i].right;
    Tree* root = new Tree;
    build(root, 0);
    for (i = 0; i < N; ++i)
        cin >> node[i];
    int temp;
    for (i = 0; i < N - 1; ++i)
        for (j = i + 1; j < N; ++j)
            if (node[i] > node[j])
            {
                temp = node[i];
                node[i] = node[j];
                node[j] = temp;
            }
    through(root);
    Tree** ed = new Tree * [N];
    int current = 0, tail = 1;
    ed[0] = root;
    while (tail < N)
    {
        if (ed[current]->nl != NULL) ed[tail] = ed[current]->nl, ++tail;
        if (ed[current]->nr != NULL) ed[tail] = ed[current]->nr, ++tail;
        ++current;

    }
    cout << (ed[0]->data);
    for (i = 1; i < N; ++i)
        cout << ' ' << (ed[i]->data);
    return 0; 
}
实在想不出来,向大佬们求助,谢谢!
  • 写回答

2条回答 默认 最新

  • 关注

    是不是递归的时候树节点出错了,可以分享一下思路

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月26日
  • 已采纳回答 9月18日
  • 创建了问题 9月18日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分