Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created July 15, 2015 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/275126c3df0191e4a1d0 to your computer and use it in GitHub Desktop.
Save joelburton/275126c3df0191e4a1d0 to your computer and use it in GitHub Desktop.
Binary Tree insertion in C
void insertNode(TreeNode **root, COMPARE compare, void* data) {
TreeNode *node = (TreeNode*) malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
if (*root == NULL) {
*root = node;
return;
}
while (1) {
if (compare((*root)->data, data) > 0) {
if ((*root)->left != NULL) {
*root = (*root)->left;
} else {
(*root)->left = node;
break;
}
} else {
if ((*root)->right != NULL) {
*root = (*root)->right;
} else {
(*root)->right = node;
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment