Skip to content

Instantly share code, notes, and snippets.

@fabianbaechli
Created April 22, 2025 14:54
Show Gist options
  • Save fabianbaechli/f7a40bf30c149a2f9ae77dcf07484389 to your computer and use it in GitHub Desktop.
Save fabianbaechli/f7a40bf30c149a2f9ae77dcf07484389 to your computer and use it in GitHub Desktop.
struct node* BSTreeDelete(struct node* root, struct node* x) {
u = root; v = NULL;
while (u != x) {
v = u;
if (x->key < u->key) u = u->lft;
else u = u->rgt;
}
if (u->rgt == NULL) {
if (v == NULL) root = u->lft;
else if (v->lft == u) v->lft = u->lft;
else v->rgt = u->lft;
else if (u->lft == NULL) {
if (v == NULL) root = u->rgt;
else if (v->lft == u) v->lft = u->rgt;
else v->rgt = u->rgt;
else {
p = x->lft;
q = p;
while (p->rgt != NULL) { q = p; p = p->rgt; }
if (v == NULL) root = p;
else if (v->lft == u) v->lft = p;
else v->rgt = p;
p->rgt = u->rgt;
if (q != p) {
q->rgt = p->lft;
p->lft = u->lft;
}
return root
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment