Create a BST by starting with root = NULL and inserting each key. The pointer-to-pointer technique lets one loop handle the empty-tree case and every other insertion alike. Measuring height and node count shows how the insertion order shapes the tree.
Remember
struct T *root = NULL;
for (int i = 0; i < n; i++) insert(&root, keys[i]);
Reference
Cheat Sheet
Keep these facts handy while you work with Creating a BST in C in C.
Topic
Detail
Start
root = NULL
Insert
insert(&root, key)
Duplicates
Return 0 and skip
Shape
Depends on input order
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: BST Insertion in C.
Example 1 — Create from an array
Ten keys, one duplicate.
C
#include <stdio.h>
#include <stdlib.h>
struct T {
int key;
struct T *left, *right;
};
static struct T *mk(int k) {
struct T *t = malloc(sizeof *t);
if (!t) exit(1);
t->key = k;
t->left = t->right = NULL;
return t;
}
static int insert(struct T **root, int k) {
struct T **pp = root;
while (*pp) {
if (k == (*pp)->key) return 0;
pp = k < (*pp)->key ? &(*pp)->left : &(*pp)->right;
}
*pp = mk(k);
return 1;
}
static void inorder(const struct T *t) {
if (!t) return;
inorder(t->left);
printf(" %d", t->key);
inorder(t->right);
}
static void free_tree(struct T *t) {
if (!t) return;
free_tree(t->left);
free_tree(t->right);
free(t);
}
static int height(const struct T *t) {
if (!t) return -1;
int a = height(t->left), b = height(t->right);
return 1 + (a > b ? a : b);
}
int main(void) {
int keys[] = {8, 3, 10, 1, 6, 14, 4, 7, 13, 6};
int n = 10, added = 0;
struct T *root = NULL;
for (int i = 0; i < n; i++) added += insert(&root, keys[i]);
printf("inserted %d of %d keys\n", added, n);
printf("inorder:");
inorder(root);
printf("\nheight: %d\n", height(root));
free_tree(root);
return 0;
}
The second 6 is detected as a duplicate and skipped.
Inorder is sorted: 1 3 4 6 7 8 10 13 14.
The longest path is 8, 3, 6, 4 which is 3 edges.
Edge Cases & Pitfalls
Check these before relying on Creating a BST in C in real programs.
sorted
Pre-sorted input
Inserting 1, 2, 3, ... yields a chain. Shuffle or use a balanced tree.
root
Updating root
Pass &root so the function can set it when the tree is empty.
Remember
Key Takeaways
Insert in a loop.
Pointer-to-pointer covers the empty case.
Input order shapes height.
One line: Create a BST by starting with root = NULL and inserting each key.
Frequently Asked Questions
Start with an empty tree and insert each array element using the BST insert function.
So the insert function can assign the new root when the tree is empty.
Continue with "BST Insertion in C" next. Trace the path a new key takes and where it attaches. The C Trees and Binary Search Trees hub lists every topic in order.