【发布时间】:2019-09-28 02:16:07
【问题描述】:
我是 C 新手,想从编写一个简单的二叉树开始。 push 和 traverse 函数都存在问题,但我花了两天时间弄清楚程序。当我编译并执行程序时,它显示分段错误。代码如下,任何帮助将不胜感激。谢谢
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
typedef struct Node
{
struct Node* right;
struct Node* left;
int* value;
} Node;
Node* init()
{
Node* t = (Node*) malloc(sizeof(Node));
t->left = NULL;
t->right = NULL;
t->value = NULL;
return t;
}
int traverse(Node* tree)
{
printf("value : %d\n", *(tree->value));
if (tree->left != NULL) {
traverse(tree->left);
} else if (tree->right != NULL){
traverse(tree->right);
}
}
void push(Node* n, int val)
{
if (n->value == NULL)
{
*(n->value) = val;
} else if (n->left == NULL && val < *(n->value)) {
n->left = init();
push(n->left, val);
} else if (n->right == NULL && val > *(n->value)) {
n->right = init();
push(n->right, val);
}
}
int main(int argc, char const *argv[])
{
srand(time(NULL));
Node* tree = init();
for (unsigned int i = 0; i < 20; ++i)
{
int val = rand() % 10;
push(tree, val);
printf("%d\n", val);
}
traverse(tree);
printf("%s\n", "End Of Program!");
return 0;
}
【问题讨论】:
-
int* value;是一个值得商榷的选择,除非这个链表打算保存ints 的动态数组。int value;更可能是您需要的。 -
traverse函数是否应该返回int?或者只是void可能会更好 -
应该可以,但出于调试目的,我没有打扰
-
btw 是 NULL C 中的指针
-
NULL是一个空指针常量。从技术上讲,它可能是0或((void *) 0)或相当于其中之一的东西。你不应该依赖它具有特定的形式。
标签: c segmentation-fault binary-tree