Last active
April 15, 2018 17:51
-
-
Save tbnbooij/3e729d134e4af3489b4c51fadda38bb3 to your computer and use it in GitHub Desktop.
Binary Tree deletion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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