CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Storing and searching ordered data - a binary tree

Each of the previous self-referential data-structures stored their values in their order of arrival, and accessed or removed them in the same order or the reverse. The actual time of insertion is immaterial, with the relative times 'embedded' in the order of the elements.

More common is to store data in a structure that embeds the relative magnitude or priority of the data. Doing so requires insertions to keep the data-structure ordered, but this makes searching much quicker as well.

Let's consider the type definition and insertion of data into a binary tree in C11:


typedef struct _bt {
    int            value;
    struct _bt     *left;
    struct _bt     *right;
} BINTREE;

BINTREE *tree_root    = NULL;


















BINTREE *tree_insert(BINTREE *t, int value)
{
    if(t == NULL) {
        BINTREE *new  = calloc(1, sizeof(BINTREE));

        if(new == NULL) {
	    perror( __func__ );
	    exit(EXIT_FAILURE);
        }
        new->value    = value;
// the calloc() call has set both left and right to NULL
        return new;
    }

    int order = (t->value - value);

    if(order > 0) {
        t->left       = tree_insert(t->left,  value);
    }
    else if(order < 0) {
        t->right      = tree_insert(t->right, value);
    }
    return t;
}

Of note:
  • we've defined a data-structure containing two pointers to other instances of the data-structure.
  • the use of the struct _bt data type is temporary, and never used again.
  • here, each element of the data-structure, each node of the tree, holds a unique instance of a data value - here, a single integer - though it's very common to hold multiple data values.
  • we insert into the tree with:
    tree_root = tree_insert(tree_root, new_value);
  • the (magnitude of the) integer data value embeds the order of the structure - elements with lesser integer values are stored 'below' and to the left of the current node, higher values to the right.
  • unlike some (more complicated) variants of the binary-tree, we've made no effort to keep the tree balanced. If we insert already sorted elements into the tree, the tree will degenerate into a list, with every node having either a NULL left or a NULL right pointer.

 


CITS2002 Systems Programming, Lecture 19, p18, 3rd October 2023.