【发布时间】:2017-01-07 18:56:18
【问题描述】:
在下面的程序中,我试图用数组 arr 中存在的值填充 BST。该程序似乎在循环中运行了很长时间,然后出现分段错误。有人可以解释一下我在这里缺少什么吗?
struct node {
int value;
struct node *left;
struct node *right;
};
void add(struct node **root, int i);
int arr[14] = {30, 50, 25, 32, 45, 55, 20, 27, 31, 43, 47, 52, 88};
int main(void)
{
struct node *root = malloc(sizeof(struct node));
root->value = 35;
root->left = NULL;
root->right = NULL;
struct node *start = root;
int i;
for (i = 0; i < 13; i++) {
add(&root, arr[i]);
root = start;
}
printf("%d\n", root->value);
printf("%p\n", root->right);
printf("%p\n", root->left);
}
void add(struct node **root, int i)
{
while ((*root) != NULL) {
printf("left: %p\n", (*root)->left);
if (i < (*root)->value) {
add(&((*root)->left), i);
} else {
add(&((*root)->right), i);
}
}
*root = malloc(sizeof(struct node));
(*root)->value = i;
(*root)->left = NULL;
(*root)->right = NULL;
}
【问题讨论】:
-
在
add()末尾分配一个新节点并返回指针是什么意思?
标签: c algorithm data-structures binary-search-tree