Binary search tree (BST) in C, visualized step by step
Every node's left subtree holds smaller keys and its right subtree the rest. Insert and search both start at the root: smaller goes left, bigger goes right, one side per level.
binary_search_tree.c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int key;
struct Node *left, *right;
} Node;
Node *insert(Node *root, int key) {
if (root == NULL) {
Node *n = malloc(sizeof(Node));
n->key = key;
n->left = n->right = NULL;
return n;
}
if (key < root->key) root->left = insert(root->left, key);
else root->right = insert(root->right, key);
return root;
}
int search(Node *root, int key) {
while (root && root->key != key)
root = key < root->key ? root->left : root->right;
return root != NULL;
}
int main(void) {
int keys[] = {8, 3, 10, 1, 6, 14};
Node *root = NULL;
for (int i = 0; i < 6; i++) root = insert(root, keys[i]);
printf("%d %d\n", search(root, 6), search(root, 7));
return 0;
}
How Binary search tree works
- Start at the root and compare the key with the current node.
- Smaller: go left; otherwise go right.
- Insert: at an empty spot, put the new node there.
- Search: an equal key is found; reaching an empty spot means it is not in the tree.
What to watch
The pathOne step left or right per level: count the nodes it passes.
Where a new node hangs6 is smaller than 8 (left) and bigger than 3 (right), so it hangs right of 3.
FAQ
What is the time complexity of searching a BST?
Proportional to the tree's height: O(log n) when it is balanced, O(n) when sorted input turns it into a line.
How do you avoid that?
Use a self-balancing tree such as an AVL or red-black tree; C++'s std::map is a red-black tree.
What does an in-order traversal of a BST give?
The keys in sorted order, smallest first.