在C中建立二叉树时出现分段错误
Segmentation fault when setting up binary tree in C
我从这个网站得到了一些想法:http://www.cprogramming.com/tutorial/c/lesson18.html
然后我写了一些代码来创建一个二叉树。如下
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int key_value;
struct node *left;
struct node *right;
} node;
void createTree(node * leaf, int depth) {
leaf->key_value = depth;
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
} else {
leaf->left = (node *) malloc(sizeof(node));
leaf->right = (node *) malloc(sizeof(node));
}
createTree(leaf->left, depth - 1);
createTree(leaf->right, depth - 1);
}
int main() {
node head;
createTree(&head, 3);
(head.left)->key_value = 5;
printf("%d\n", head.left->key_value);
return 0;
}
它编译得很好,但是当我 运行 它时,我得到了一个分段错误。这个想法是从一个名为 head 的节点开始,然后赋予该值 3,然后为其两个子节点赋予值 2,等等,直到我们到达深度 == 0,此时我们不再制作任何叶子。
您有无限递归,因为您没有在 depth == 0
上 return
,而是在 createTree
上再次递归。
void createTree(node * leaf, int depth) {
leaf->key_value = depth;
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
return;
}
leaf->left = malloc(sizeof(node));
leaf->right = malloc(sizeof(node));
createTree(leaf->left, depth - 1);
createTree(leaf->right, depth - 1);
}
它是一个无限递归,在基本条件下必须总是有一些东西可以 return 来跳出递归循环:
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
return; // edit
}
我从这个网站得到了一些想法:http://www.cprogramming.com/tutorial/c/lesson18.html
然后我写了一些代码来创建一个二叉树。如下
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int key_value;
struct node *left;
struct node *right;
} node;
void createTree(node * leaf, int depth) {
leaf->key_value = depth;
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
} else {
leaf->left = (node *) malloc(sizeof(node));
leaf->right = (node *) malloc(sizeof(node));
}
createTree(leaf->left, depth - 1);
createTree(leaf->right, depth - 1);
}
int main() {
node head;
createTree(&head, 3);
(head.left)->key_value = 5;
printf("%d\n", head.left->key_value);
return 0;
}
它编译得很好,但是当我 运行 它时,我得到了一个分段错误。这个想法是从一个名为 head 的节点开始,然后赋予该值 3,然后为其两个子节点赋予值 2,等等,直到我们到达深度 == 0,此时我们不再制作任何叶子。
您有无限递归,因为您没有在 depth == 0
上 return
,而是在 createTree
上再次递归。
void createTree(node * leaf, int depth) {
leaf->key_value = depth;
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
return;
}
leaf->left = malloc(sizeof(node));
leaf->right = malloc(sizeof(node));
createTree(leaf->left, depth - 1);
createTree(leaf->right, depth - 1);
}
它是一个无限递归,在基本条件下必须总是有一些东西可以 return 来跳出递归循环:
if (depth == 0) {
leaf->left = 0;
leaf->right = 0;
return; // edit
}