【发布时间】: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