【问题标题】:Sorted by Binary search tree C [closed]按二叉搜索树 C 排序
【发布时间】:2021-12-17 09:51:16
【问题描述】:

我需要使用二叉树对数组进行排序,但我的代码在第 4 次测试中失败。我不知道它有什么问题,我认为这是一种测试,这种测试有很多相同的数字或奇怪的数字顺序。我也写过这个 Binary tree insertion sort in C ,但该代码在第 4 次测试时也出错了。 我在任务中有二进制输入/输出。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>


typedef struct node
{
    int value;
    struct node *right,*left;
}tree;



tree* createElement(int value)
{
    tree *cur;
    cur = malloc(sizeof(tree));
    cur->value = value;
    cur->left = NULL;
    cur->right = NULL;
    return cur;
}

tree* addElem(tree *root, int x) {
    if (!root) {
        return createElement(x);
    }
    else if (x > root->value){
        root->right = addElem(root->right, x);
    }
    else {
        root->left = addElem(root->left, x);
    }
    return root;
}


void inorder(tree *root,FILE *s)
{
    if(root!=NULL)
    {
        inorder(root->left,s);
        fwrite(&root->value,sizeof(root->value),1,s);
        inorder(root->right,s);
    }
}

int main()
{
    FILE *f = fopen("input.bin","rb");
    FILE *s = fopen("output.bin","wb");
    tree *root;
    uint32_t n;
    int32_t number;
    fread(&n, sizeof(n), 1, f);
    fread(&number, sizeof(number), 1, f);
    root = createElement(number);
    for(int i = 1 ;i < n; i++){
        fread(&number, sizeof(number), 1, f);
        addElem(root,number);
    }
    inorder(root,s);
    return 0;
}

【问题讨论】:

  • 什么是“第四次测试”?测试输入是什么样的?
  • 当您说“我的代码失败”时,请更加具体。
  • 也许递归导致某些测试用例的堆栈溢出?
  • @500 - Internal Server Error Re "addElem just return if local root is non-NULL",不,它先添加节点。
  • 不处理n==0的情况

标签: c binary-search-tree


【解决方案1】:

它不处理n == 0的情况。

tree *root;
root = createElement(number);
for(int i = 1 ;i < n; i++){
    fread(&number, sizeof(number), 1, f);
    addElem(root,number);
}

应该是

tree *root = NULL;
if (n > 0) {
    root = createElement(number);
    for(int i = 1 ;i < n; i++){
        fread(&number, sizeof(number), 1, f);
        addElem(root,number);
    }
}

或者只是

tree *root = NULL;
for(int i = 0 ;i < n; i++){
    fread(&number, sizeof(number), 1, f);
    root = addElem(root,number);
}

【讨论】:

  • 现在我的程序在接下来的一项测试中“超过了时间限制”(我正在努力让大学工作)
  • 这是一种非常慢的排序方式(O(N^2))。想象一下输入是否已经排序或需要反转。您的树将有效地拥有一个链表。
  • 是的,但我的任务是使用二叉搜索树对数组进行排序,所以应该有一种方法可以足够快地对输入进行排序
  • 人们会使用某种balanced tree 来提高更大集合的性能。当然,你还没有确定你有性能问题。
  • 如何在不使用平衡树的情况下通过特殊输入加快此过程?我如何在这段代码中考虑这些情况?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多