ZetCode

Binary trees in K&R C

last modified December 5, 2026 K&R C 1978

A binary tree is made of nodes that point to two other nodes, a left and a right child. In a binary search tree, every value in the left subtree of a node is smaller than the value of the node, and every value in the right subtree is not smaller. A value can then be found, or its place found, by going down from the root and choosing a side at each node. The book uses such a tree to count the words of its input. This article builds trees of numbers first, then the word counter.

A tree of numbers

A tree is reached through a pointer to its root, and an empty tree is a null pointer, as an empty list was in the linked lists article. The functions that work on a tree are recursive, because each subtree is a tree itself.

numtree.c
#include <stdio.h>
#include <stdlib.h>

struct tnode {
    int value;
    struct tnode *left;         /* smaller values */
    struct tnode *right;        /* larger values */
};

/* add value to the tree at p; return the root of the subtree */
struct tnode *addtree(p, value)
struct tnode *p;
int value;
{
    if (p == NULL) {
        p = (struct tnode *) malloc(sizeof(struct tnode));
        if (p == NULL) {
            fprintf(stderr, "out of memory\n");
            exit(1);
        }
        p->value = value;
        p->left = p->right = NULL;
    } else if (value < p->value)
        p->left = addtree(p->left, value);
    else
        p->right = addtree(p->right, value);
    return p;
}

/* print the tree in order: left subtree, node, right subtree */
int treeprint(p)
struct tnode *p;
{
    if (p != NULL) {
        treeprint(p->left);
        printf("%d ", p->value);
        treeprint(p->right);
    }
    return 0;
}

int main()
{
    static int v[] = { 31, 4, 15, 9, 26, 5, 3, 58, 97, 23 };
    struct tnode *root;
    int i;

    root = NULL;
    for (i = 0; i < 10; i++)
        root = addtree(root, v[i]);
    treeprint(root);
    printf("\n");
    return 0;
}

addtree adds a value to the tree whose root is p and returns the root. An empty tree gets a new node with two empty subtrees. Otherwise the value goes into the left subtree if it is smaller than the value of the node, and into the right one if not; the recursive call returns the root of the subtree, which is stored back in the node. The first value becomes the root of the whole tree. treeprint prints the left subtree, the node, and the right subtree, in this order, so it prints the values sorted.

$ gcc -std=c89 -pedantic -Wall -Wextra -o numtree numtree.c
$ ./numtree
3 4 5 9 15 23 26 31 58 97 

Searching a tree

To find a value, the search goes down from the root, to the left for a smaller value and to the right for a larger one, until it finds the value or an empty subtree. It needs no recursion, because it follows a single path. The functions of the first program go into a file of their own, so that the following programs can use them.

tree.h
struct tnode {
    int value;
    struct tnode *left;         /* smaller values */
    struct tnode *right;        /* larger values */
};

struct tnode *addtree();
int treeprint();

The header declares the node and the two functions.

tree.c
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"

struct tnode *addtree(p, value)
struct tnode *p;
int value;
{
    if (p == NULL) {
        p = (struct tnode *) malloc(sizeof(struct tnode));
        if (p == NULL) {
            fprintf(stderr, "out of memory\n");
            exit(1);
        }
        p->value = value;
        p->left = p->right = NULL;
    } else if (value < p->value)
        p->left = addtree(p->left, value);
    else
        p->right = addtree(p->right, value);
    return p;
}

int treeprint(p)
struct tnode *p;
{
    if (p != NULL) {
        treeprint(p->left);
        printf("%d ", p->value);
        treeprint(p->right);
    }
    return 0;
}

tree.c holds addtree and treeprint from the first program.

find.c
#include <stdio.h>
#include "tree.h"

int nvisits;            /* nodes looked at by the last search */

/* find value in the tree; return its node or NULL */
struct tnode *find(p, value)
struct tnode *p;
int value;
{
    nvisits = 0;
    while (p != NULL) {
        nvisits++;
        if (value == p->value)
            return p;
        p = value < p->value ? p->left : p->right;
    }
    return NULL;
}

int main()
{
    static int v[] = { 31, 4, 15, 9, 26, 5, 3, 58, 97, 23 };
    static int keys[] = { 31, 23, 97, 10 };
    struct tnode *root;
    int i;

    root = NULL;
    for (i = 0; i < 10; i++)
        root = addtree(root, v[i]);
    for (i = 0; i < 4; i++)
        if (find(root, keys[i]) != NULL)
            printf("%d found at depth %d\n", keys[i], nvisits);
        else
            printf("%d not found, %d nodes looked at\n", keys[i], nvisits);
    return 0;
}

find moves p down the tree one node at a time and counts the nodes it looks at in nvisits. The program builds the tree of the first example and looks for four values. The root, 31, is found at once. A value that is not in the tree is reported when the search falls off the bottom of the tree.

$ gcc -std=c89 -pedantic -Wall -Wextra -o find find.c tree.c
$ ./find
31 found at depth 1
23 found at depth 5
97 found at depth 3
10 not found, 4 nodes looked at

The shape of a tree

The speed of a search depends on the height of the tree, the number of nodes on its longest path from the root down. The same values can make a short tree or a tall one, depending on the order in which they arrive.

shape.c
#include <stdio.h>
#include "tree.h"

int height(p)           /* nodes on the longest path from p down */
struct tnode *p;
{
    int l, r;

    if (p == NULL)
        return 0;
    l = height(p->left);
    r = height(p->right);
    return 1 + (l > r ? l : r);
}

/* print the tree on its side: the root on the left */
int sideways(p, depth)
struct tnode *p;
int depth;
{
    int i;

    if (p != NULL) {
        sideways(p->right, depth + 1);
        for (i = 0; i < depth; i++)
            printf("    ");
        printf("%d\n", p->value);
        sideways(p->left, depth + 1);
    }
    return 0;
}

int build(v, n)
int v[];
int n;
{
    struct tnode *root;
    int i;

    root = NULL;
    for (i = 0; i < n; i++)
        root = addtree(root, v[i]);
    sideways(root, 0);
    printf("height %d\n\n", height(root));
    return 0;
}

int main()
{
    static int mixed[] = { 4, 2, 6, 1, 3, 5, 7 };
    static int sorted[] = { 1, 2, 3, 4, 5, 6, 7 };

    build(mixed, 7);
    build(sorted, 7);
    return 0;
}

height is 0 for an empty tree; otherwise it is one more than the height of the taller subtree. sideways prints the tree turned by a quarter: the root is on the left, the right subtree above it, and each level is indented four more spaces. build makes a tree from an array, prints it, and prints its height. The values 1 to 7 are added twice, once in a mixed order and once sorted.

$ gcc -std=c89 -pedantic -Wall -Wextra -o shape shape.c tree.c
$ ./shape
        7
    6
        5
4
        3
    2
        1
height 3

                        7
                    6
                5
            4
        3
    2
1
height 7

In the mixed order, each node has two children, and seven values fit in three levels. The sorted values all go to the right, and the tree becomes a list with a height of seven. A search in such a tree is no faster than in a list. Input that is already sorted is common, so a program that uses a simple tree should not expect it to stay short.

Freeing a tree

A node can only be freed after its subtrees are freed, because the node holds the only pointers to them. Freeing is therefore done in postorder: the left subtree, the right subtree, and then the node.

freeing.c
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"

/* free both subtrees, then the node; return the nodes freed */
int freetree(p)
struct tnode *p;
{
    int n;

    if (p == NULL)
        return 0;
    n = freetree(p->left) + freetree(p->right);
    free((char *) p);
    return n + 1;
}

int main()
{
    struct tnode *root;
    int i;

    root = NULL;
    for (i = 0; i < 20; i++)
        root = addtree(root, (i * 7) % 20);
    treeprint(root);
    printf("\n%d nodes freed\n", freetree(root));
    return 0;
}

freetree returns the number of nodes it freed: the nodes of both subtrees plus one. The program adds the numbers from 0 to 19 in the scrambled order that (i * 7) % 20 gives, prints the tree, and frees it.

$ gcc -std=c89 -pedantic -Wall -Wextra -o freeing freeing.c tree.c
$ ./freeing
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
20 nodes freed

Counting words

The book's example of a tree counts how often each word occurs in its input. The set of words is not known in advance, so a table of keywords, as in the structures article, cannot be used. Each node holds a word and its count, and the tree keeps the words in alphabetical order.

getword.c
#include <stdio.h>
#include <ctype.h>

/* read the next word into w, in lower case; return EOF at the end */
int getword(w, lim)
char *w;
int lim;
{
    int c;

    while ((c = getchar()) != EOF && !isalpha(c))
        ;
    if (c == EOF)
        return EOF;
    *w++ = tolower(c);
    while (--lim > 1 && (c = getchar()) != EOF && isalpha(c))
        *w++ = tolower(c);
    *w = '\0';
    return 1;
}

getword skips everything up to the next letter and collects the letters that follow, converted to lower case, so that The and the count as one word. It is the function of the structures article with tolower added and without the digits.

wfreq.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXWORD 20

struct tnode {
    char *word;
    int count;
    struct tnode *left;
    struct tnode *right;
};

int getword();

char *strsave(s)        /* a copy of s in storage from malloc */
char *s;
{
    char *p;

    if ((p = malloc(strlen(s) + 1)) != NULL)
        strcpy(p, s);
    return p;
}

/* count w in the tree at p */
struct tnode *addword(p, w)
struct tnode *p;
char *w;
{
    int cond;

    if (p == NULL) {
        p = (struct tnode *) malloc(sizeof(struct tnode));
        if (p == NULL || (p->word = strsave(w)) == NULL) {
            fprintf(stderr, "out of memory\n");
            exit(1);
        }
        p->count = 1;
        p->left = p->right = NULL;
    } else if ((cond = strcmp(w, p->word)) == 0)
        p->count++;
    else if (cond < 0)
        p->left = addword(p->left, w);
    else
        p->right = addword(p->right, w);
    return p;
}

int ndistinct;

int printrep(p)         /* print the words that occur more than once */
struct tnode *p;
{
    if (p != NULL) {
        printrep(p->left);
        ndistinct++;
        if (p->count > 1)
            printf("%3d %s\n", p->count, p->word);
        printrep(p->right);
    }
    return 0;
}

int main()
{
    struct tnode *root;
    char word[MAXWORD];

    root = NULL;
    while (getword(word, MAXWORD) != EOF)
        root = addword(root, word);
    printrep(root);
    printf("%d different words\n", ndistinct);
    return 0;
}

A node has a pointer to its word, not an array: words have different lengths. strsave copies a word into storage from malloc, one byte longer than the word for the terminating '\0', and returns NULL if there is no room. addword stops the program if either allocation fails. The array word in main is reused for every word, so the tree must keep a copy. addword compares with strcmp: an equal word increments the count, and a different one goes left or right. printrep walks the tree in order, counts the distinct words, and prints those that occur more than once.

poem.txt
The tide comes in without a sound,
it fills the harbour stone by stone,
and every boat that lay aground
is lifted up and rides alone.

The gulls go quiet one by one,
the lamps are lit along the quay;
the tide goes out when night is done
and takes the boats back out to sea.

The input is the poem of the character input article.

$ gcc -std=c89 -pedantic -Wall -Wextra -o wfreq wfreq.c getword.c
$ ./wfreq < poem.txt
  3 and
  2 by
  2 is
  2 one
  2 out
  2 stone
  7 the
  2 tide
42 different words

Source

Dennis Ritchie: C Reference Manual (1975)

Binary search tree on Wikipedia

In this article we have built binary trees in K&R C: recursive insertion and in-order printing, searching, the height and shape of a tree, freeing a tree in postorder, and the word-frequency tree of the book. The next article finds words in hash tables.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.