Skip to content

Instantly share code, notes, and snippets.

@abatilo
Created April 21, 2016 23:41
Show Gist options
  • Save abatilo/88fc70da11d4eadc01dd0400e4565b46 to your computer and use it in GitHub Desktop.
Save abatilo/88fc70da11d4eadc01dd0400e4565b46 to your computer and use it in GitHub Desktop.
node *insert(node *root, int value) {
node *current = root;
node *prev;
if (root == NULL) {
root = (node *)malloc(sizeof(node));
root->data = value;
root->left = NULL;
root->right = NULL;
return root;
}
while (current != NULL) {
if (value <= current->data) {
prev = current;
current = current->left;
} else {
prev = current;
current = current->right;
}
}
node *next = (node *)malloc(sizeof(node));
next->data = value;
next->left = NULL;
next->right = NULL;
if (value <= prev->data) {
prev->left = next;
} else {
prev->right = next;
}
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment