Skip to content

Instantly share code, notes, and snippets.

@tbnbooij
Last active April 15, 2018 17:51
Show Gist options
  • Save tbnbooij/3e729d134e4af3489b4c51fadda38bb3 to your computer and use it in GitHub Desktop.
Save tbnbooij/3e729d134e4af3489b4c51fadda38bb3 to your computer and use it in GitHub Desktop.
Binary Tree deletion
#include "tree.h"
Node* Tree_get_largest(Node* root) {
Node* c = root;
while (c->right)
c = c->right;
return c;
}
Node* Tree_delete_recursively(Node* node, int data) {
if (!node) return NULL;
if (data < node->data)
node->left = Tree_delete_recursively(node->left, data);
else if (data > node->data)
node->right = Tree_delete_recursively(node->right, data);
else {
if (!node->left) {
Node* tmp = node->right;
free(node);
return tmp;
}
if (!node->right) {
Node* tmp = node->left;
free(node);
return tmp;
}
Node* largest = Tree_get_largest(node->left);
node->data = largest->data;
node->left = Tree_delete_recursively(node->left, largest->data);
}
return node;
}
void Tree_delete(Node* node, int data) {
Tree_delete_recursively(node, data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment