Binary tree in C: solved insertion and search exercise

Binary tree in C: solved exercise

If you searched for binary tree in C solved exercise, this page gives you a basic BST with insert and search.

Problem statement

Implement a binary search tree with:

  • value insertion,
  • value lookup,
  • output showing if value exists.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int v;
    struct Node *left, *right;
} Node;

Node *insert(Node *r, int v) {
    if (!r) {
        Node *n = malloc(sizeof(Node));
        if (!n) return NULL;
        n->v = v; n->left = n->right = NULL;
        return n;
    }

    if (v < r->v) r->left = insert(r->left, v);
    else if (v > r->v) r->right = insert(r->right, v);

    return r;
}

int search(Node *r, int v) {
    if (!r) return 0;
    if (r->v == v) return 1;
    if (v < r->v) return search(r->left, v);
    return search(r->right, v);
}

void free_tree(Node *r) {
    if (!r) return;
    free_tree(r->left);
    free_tree(r->right);
    free(r);
}

int main(void) {
    Node *r = NULL;
    r = insert(r, 20);
    r = insert(r, 10);
    r = insert(r, 30);

    printf("Has 10: %d\n", search(r, 10));
    printf("Has 40: %d\n", search(r, 40));

    free_tree(r);
    return 0;
}

Expected output

1
2
Has 10: 1
Has 40: 0

Common mistakes

  • Not defining duplicate-value behavior.
  • Breaking BST ordering property.
  • Skipping final memory cleanup.

Practical use

Trees are still used for in-memory indexes, hierarchy models, and search features.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.