问题
I am trying to create a program which which takes a list of words as an input, and sorts them into a binary tree, in order to allow them to be found, e.g. like a dictionary. This is what I have done so far, but am getting a segmentation error with newEl -> el = input;
I know this is because it is trying to point to a NULL el, when the tree is first created, but i'm not sure what the best way to improve my code would be. Anyone have any ideas? Thanks.
struct node *tra(struct node * start, Type input) {
struct node * thisNode = start;
if (thisNode == NULL)
Type current = thisNode -> el;
if (strcmp(input, current) > 0)
return tra(thisNode -> right, input);
else if (strcmp(input, current) < 0)
return tra(thisNode -> left, input);
else
return thisNode;
}
}
Ta insert(Type input, Ta ta) {
if ((find(input, ta)) == FALSE) {
newEl -> el = input;
}
return ta;
}
Boolean find(Type input, Ta ta) {
if (tra(ta -> head, input) == NULL)
return FALSE;
}
回答1:
This is a pointer to pointer equivalent:
typedef char *Type;
struct node {
struct node *left , *right;
Type payload;
};
struct node **find_pp(struct node **pp, Type input) {
struct node *thisNode ;
while ( thisNode = *pp ) {
int diff;
diff = strcmp(input, thisNode->payload);
if (!diff) break;
pp = (diff <0) ? &thisNode->left : &thisNode->right;
}
return pp;
}
Boolean find(struct node *root, Type thing)
{
struct node **pp;
pp = find_pp( &root, thing);
return (*pp) ? True : False;
}
void insert (struct node **pp, Type thing)
{
struct node *newNode;
pp = find_pp (pp, thing);
if (*pp) return; /* already exists */
*pp = newNode = malloc (sizeof *newnode);
newNode->payload = strdup(thing);
newNode->left = NULL;
newNode->right = NULL;
return;
}
a few notes:
- inserting a node into a tree means: assigning to a pointer that was previously NULL
- the empty tree is also a tree: just a pointer (to the root of the tree) that happens to be null
- finding a node in a tree means: finding the place ( :=pointer) where is should be (if it existed)
- if it does not exists, this pointer is exactly the place where it should be inserted to bring it into existence
- drawing a diagram (with paper and pencil) will help.
回答2:
Since you already know what the problem is you should resolve it. Allocate the node and insert it.
Ta insert(Type input, Ta ta) {
if ((find(input, ta)) == FALSE) {
// call to tra will fail. this is the place to create a new node
struct node *newEl = (struct node*) malloc(sizeof(struct node));
newEl -> el = input;
newEl -> left = 0;
newEl -> right = 0;
// do the insertion ....
}
}
回答3:
Seems like you want to create a new node, but I don't see anywhere where you allocate space for a new node, like:
newEl = (struct node*)malloc(sizeof(struct node));
Good luck!
来源:https://stackoverflow.com/questions/14922802/c-binary-search-tree-implementation-insert