I’m trying to implement a binary search tree (BST) in C. I have tried to add several elements to the BST, but when I add the third one, the code doesn’t work. I debug it in gdb and find that when it executes malloc
for the new node, the second node’s parent changes from a correct address value to 0x13
.
Since I feel that there is no relation between the new node’s memory allocation and the old node’s parent, I have no idea why does this happens…
Here is my InsertBST
function:
int InsertBST(Bst *p, int val)
{
PNode pnode = (PNode)malloc(sizeof(PNode));
if (pnode != NULL)
{
pnode->data = val;
pnode->lc = NULL;
pnode->rc = NULL;
if (p->root == NULL)
{
pnode->parent = NULL;
p->root = pnode;
p->size++;
return 1;
}
else
{
PNode tem = FindVal(p->root, val);
if (tem != NULL)
{
printf("Sorry, the value %d has appeared!\n", val);
return 0;
}
else
{
tem = p->root;
while (tem->lc != NULL && tem->rc != NULL)
{
if (tem->data > val)
tem = tem->lc;
else
tem = tem->rc;
}
pnode->parent = tem;
if (tem->data > val)
{
tem->lc = pnode;
}
else
{
tem->rc = pnode;
}
p->size++;
}
return 1;
}
}
else
{
printf("Allocate memory failed!\n");
return 0;
}
}
p
is pointer to a structure like this:
typedef struct BST
{
PNode root;
int size;
}Bst;
and PNode
is pointer to a structure like this:
typedef struct NODE
{
int data;
PNode lc;
PNode rc;
PNode parent;
}Node;