To insert a key, compare it with the current node: go left if smaller, right if larger, until you reach a NULL child, then attach a new node there. New keys are always inserted as leaves, so existing nodes never move. Time is O(h).
Remember
while (cur) {
parent = cur;
cur = (k < cur->key) ? cur->left : cur->right;
}
/* attach new node to parent */
Reference
Cheat Sheet
Keep these facts handy while you work with BST Insertion in C in C.
Topic
Detail
Rule
Always inserted as a leaf
Compare
Smaller left, larger right
Time
O(h)
Duplicates
Skip or count
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: BST Search in C.
Example 1 — Trace inserting 15
The tree has root 10 with children 5 and 20.
C
#include <stdio.h>
#include <stdlib.h>
struct T { int key; struct T *left, *right; };
static void inorder(const struct T *t) {
if (!t) return;
inorder(t->left);
printf(" %d", t->key);
inorder(t->right);
}
int main(void) {
struct T n5 = {5, NULL, NULL}, n20 = {20, NULL, NULL};
struct T root = {10, &n5, &n20};
int k = 15;
struct T *parent = NULL, *cur = &root;
while (cur) {
parent = cur;
if (k < cur->key) {
printf("%d < %d, go left\n", k, cur->key);
cur = cur->left;
} else {
printf("%d > %d, go right\n", k, cur->key);
cur = cur->right;
}
}
struct T *n = malloc(sizeof *n);
if (!n) return 1;
n->key = k;
n->left = n->right = NULL;
if (k < parent->key) parent->left = n;
else parent->right = n;
printf("inserted %d as %s child of %d\n", k, k < parent->key ? "left" : "right", parent->key);
printf("inorder:");
inorder(&root);
printf("\n");
free(n);
return 0;
}
Output
15 > 10, go right
15 < 20, go left
inserted 15 as left child of 20
inorder: 5 10 15 20
How It Works
15 is greater than 10, so it goes right to 20.
15 is less than 20, and 20's left child is empty.
The new node attaches there as a leaf.
Edge Cases & Pitfalls
Check these before relying on BST Insertion in C in real programs.
parent
Losing the parent
Track parent while descending; after the loop cur is NULL.
root
Empty tree
Handle root == NULL or use pointer-to-pointer.
Remember
Key Takeaways
Descend, then attach.
Always a leaf.
O(h).
One line: To insert a key, compare it with the current node: go left if smaller, right if larger, until you reach a NULL child, then attach a new node there.
Frequently Asked Questions
As a leaf: the position where a search for the key would have ended at a NULL child.
O(h): O(log n) for a balanced tree and O(n) in the worst case.
Continue with "BST Search in C" next. Search a BST iteratively and count comparisons. The C Trees and Binary Search Trees hub lists every topic in order.