I have written a recursive insert algorithm for a BST. However, there is a bug in the algorithm. If anyone could please give me a pointer, it will be greatly appreciated. Please not that y = NULL in the initial call.
void insert_recursive(Node **root, Node *z, Node *y) {
// z is the pointer to the node being inserted, and y keeps track of z's parent
Node *x = *root;
if (x != NULL) {
y = x;
if (z->val < x->val)
insert_recursive(&(x->left), z, y);
else
insert_recursive(&(x->right), z, y);
}
else {
if (y == NULL)
{ *r = z; printf("inserting root, %d\n", z->val); }
else if (z->val < x->val)
{ y->left = z; printf("inserting left of %d, item %d\n", y->val, z->val); }
else
{ y->right = z; printf("inserting right of %d, item %d\n", y->val, z->val); }
}
}
It may not be the only problem, but your line
occurs in the
elseclause ofif (x != NULL). In other words, x is guaranteed to be NULL here.