Trees are used throughout computing. This page looks closely at two binary-tree applications (binary search trees and expression trees) and surveys the others.
Binary search trees
Definition 6.15 · Binary search tree (BST)
A binary search tree is a binary tree in which, for every node, all keys in its left subtree are smaller than its key and all keys in its right subtree are larger.
Searching starts at the root and goes left or right at each node, like binary search. For a tree of height h h h a search takes O ( h ) O(h) O ( h ) comparisons: O ( log n ) O(\log n) O ( log n ) if the tree is balanced, O ( n ) O(n) O ( n ) if it is skewed. An inorder traversal of a BST lists the keys in sorted order . Unit 7 studies BSTs and balanced variants (AVL, red-black, B-trees) in detail.
Example 6.16 Build a BST, print it sorted, and search it
Goal. Insert 14, 10, 16, 8, 11, 15, 18 (the tree of Figure 6.14), print the inorder traversal, and search for 11 and 13.
Program. insert handles the empty tree by returning the new node.
C · bst.c Copy #include <stdio.h>
#include <stdlib.h>
typedef struct node {
struct node * left;
int key;
struct node * right;
} Node;
/* Insert key into the BST rooted at root; returns the (possibly new) root.
Works for an empty tree. Equal keys go to the right here. */
Node * insert(Node * root, int key)
{
if (root == NULL ) {
Node * n = malloc( sizeof * n);
if (n == NULL ) {
fprintf(stderr, "out of memory \n " );
exit(EXIT_FAILURE);
}
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;
}
/* Search, printing the keys compared. */
int search( const Node * t, int key)
{
printf( "search %2d:" , key);
while (t != NULL ) {
printf( " %d" , t->key);
if (key == t->key) {
printf( " -> found \n " );
return 1 ;
}
t = (key < t->key) ? t->left : t->right;
}
printf( " -> not found \n " );
return 0 ;
}
void inorder( const Node * t)
{
if (t == NULL ) return ;
inorder(t->left);
printf( "%d " , t->key);
inorder(t->right);
}
void free_tree(Node * t)
{
if (t == NULL ) return ;
free_tree(t->left);
free_tree(t->right);
free(t);
}
int main( void )
{
int keys [] = { 14 , 10 , 16 , 8 , 11 , 15 , 18 };
Node * root = NULL ; /* start with an empty tree */
for ( int i = 0 ; i < 7 ; i ++ )
root = insert(root, keys[i]);
printf( "inorder (sorted): " );
inorder(root);
printf( " \n " );
search(root, 11 );
search(root, 13 );
free_tree(root);
return 0 ;
}
Run it.
Output Copy inorder (sorted): 8 10 11 14 15 16 18
search 11: 14 10 11 -> found
search 13: 14 10 11 -> not found
Result. Inorder gives 8 10 11 14 15 16 18 (sorted); the search for 11 compares 14, 10, 11, and the search for 13 fails after the same three comparisons.
Expression trees
An expression tree is evaluated bottom-up: a leaf’s value is its operand; an internal node’s value is its operator applied to the values of its two subtrees. This is a postorder computation. An expression tree can be built from a postfix expression with a stack of subtrees: push a leaf for each operand; for each operator, pop two subtrees and push a new node with them as children.
Example 6.17 Build, print and evaluate expression trees
Goal. Build the trees for Figure 6.8, for Figure 6.15, and for 1*5+8-6 as C would read it, then print and evaluate each.
Program.
C · expr_tree.c Copy #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct node {
struct node * left;
char sym; /* operator, or a digit for a leaf */
struct node * right;
} Node;
Node * make( char s, Node * l, Node * r)
{
Node * n = malloc( sizeof * n);
if (n == NULL ) {
fprintf(stderr, "out of memory \n " );
exit(EXIT_FAILURE);
}
n->sym = s; n->left = l; n->right = r;
return n;
}
/* Build an expression tree from a postfix string of single digits
and operators, using a stack of subtrees (as in Unit 4). */
Node * from_postfix( const char * p)
{
Node * stack[ 32 ];
int top = - 1 ;
for (; * p; p ++ ) {
if (isdigit(( unsigned char ) * p))
stack[ ++ top] = make( * p, NULL , NULL );
else {
Node * r = stack[top -- ], * l = stack[top -- ];
stack[ ++ top] = make( * p, l, r);
}
}
return stack[top];
}
void inorder( const Node * t) /* fully parenthesised infix */
{
if (t == NULL ) return ;
if (t->left) printf( "(" );
inorder(t->left);
printf( "%c" , t->sym);
inorder(t->right);
if (t->left) printf( ")" );
}
void preorder( const Node * t) { if (t) { printf( "%c " , t->sym); preorder(t->left); preorder(t->right); } }
void postorder( const Node * t) { if (t) { postorder(t->left); postorder(t->right); printf( "%c " , t->sym); } }
/* Evaluate: a leaf is its value; otherwise evaluate both children
(a postorder computation) and apply the operator. */
double eval( const Node * t)
{
if (t->left == NULL )
return t->sym - '0' ;
double a = eval(t->left), b = eval(t->right);
switch (t->sym) {
case '+' : return a + b;
case '-' : return a - b;
case '*' : return a * b;
default : return a / b;
}
}
void free_tree(Node * t) { if (t) { free_tree(t->left); free_tree(t->right); free(t); } }
void show( const char * postfix)
{
Node * t = from_postfix(postfix);
printf( "infix : " ); inorder(t); printf( " \n " );
printf( "preorder : " ); preorder(t); printf( " \n " );
printf( "postorder: " ); postorder(t); printf( " \n " );
printf( "value : %g \n\n " , eval(t));
free_tree(t);
}
int main( void )
{
show( "42/7*31-+" ); /* Figure 6.8 */
show( "15*86-+" ); /* Figure 6.15: (1*5) + (8-6) */
show( "15*8+6-" ); /* 1*5+8-6 as C reads it: ((1*5)+8)-6 */
return 0 ;
}
Run it.
Output Copy infix : (((4/2)*7)+(3-1))
preorder : + * / 4 2 7 - 3 1
postorder: 4 2 / 7 * 3 1 - +
value : 16
infix : ((1*5)+(8-6))
preorder : + * 1 5 - 8 6
postorder: 1 5 * 8 6 - +
value : 7
infix : (((1*5)+8)-6)
preorder : - + * 1 5 8 6
postorder: 1 5 * 8 + 6 -
value : 7
Result. Figure 6.8 evaluates to 16. Figure 6.15 has + at the root, so it represents (1*5)+(8-6); the expression 1*5+8-6 with normal precedence is ((1*5)+8)-6, a different tree with - at the root, although both happen to give 7.
Other applications
Area Tree used File systems and folders General trees (and B-trees on disk) Databases and indexes B-trees, B+ trees (Unit 7) Fast searching BSTs, AVL and red-black trees (Unit 7) Compilers Syntax trees and expression trees Data compression Huffman trees Games and AI Game trees (e.g. tic-tac-toe), decision trees Graphics Quadtrees, octrees Text search Tries (Unit 11)
A game tree has the current position at the root and the positions after each possible move as children. Its size grows very fast: with just two choices per move, a game of 10 moves already gives 2 10 − 1 = 1023 2^{10} - 1 = 1023 2 10 − 1 = 1023 nodes, so real game programs search only part of the tree.
Key idea
Inorder traversal of a binary search tree gives sorted keys and a search takes O ( h ) O(h) O ( h ) steps; an expression tree is evaluated by a postorder computation, and its structure, not the written string, fixes the order of operations.
TEE Exam note
For “applications of binary trees” explain BSTs (definition, search, inorder gives sorted order) and expression trees (construction from postfix, evaluation, traversals give prefix/infix/postfix) in detail, and list three further applications. Drawing the expression tree of a given infix expression is a common short question: find the operator applied last ; it is the root.
Common mistake
Checking the BST property only between a node and its children. Every key in the whole left subtree must be smaller (and every key in the right subtree larger), not just the immediate children.
Common mistake
Drawing the expression tree from left to right as the expression is written. The root is the operator evaluated last (lowest precedence, rightmost among equals for left-associative operators), not the first operator in the string.
Key takeaways
BST: left subtree < node < right subtree; search O ( h ) O(h) O ( h ) ; inorder lists keys in sorted order.
Expression tree: leaves are operands, internal nodes operators; evaluate in postorder.
Build an expression tree from postfix with a stack of subtrees.
Trees also appear in file systems, databases, compilers, compression, games and graphics.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice Keys 50, 30, 70, 20, 40 are inserted into an empty BST in this order. What is the inorder traversal?
A 50 30 20 40 70 B 20 40 30 70 50 C 20 30 40 50 70 D 50 30 70 20 40
Check answer
Show answer Answer: C. 20 30 40 50 70
Inorder of a BST is always sorted, whatever the insertion order. “50 30 20 40 70” is the preorder of this tree.
Question 2 · multiple choice Which comparisons are made when searching for 40 in the BST of question 1?
A 20, 30, 40 B 50, 30, 40 C 50, 70, 40 D 50 only
Check answer
Show answer Answer: B. 50, 30, 40
40 < 50: go left to 30; 40 > 30: go right to 40: found. A search follows one root-to-node path.
Question 3 · multiple choice Which operator is at the root of the expression tree for a - b * c + d?
A -B *C +D d
Check answer
Show answer Answer: C. +
The expression is ((a - (b * c)) + d); the last operation is +. The root is the operator applied last.
Question 4 · multiple choice What does this program print?
C · q6-eval.c Copy #include <stdio.h>
#include <stddef.h>
typedef struct n {
struct n * l;
char s;
struct n * r;
} N;
int eval( const N * t)
{
if (t->l == NULL )
return t->s - '0' ;
int a = eval(t->l), b = eval(t->r);
return t->s == '+' ? a + b : t->s == '-' ? a - b : a * b;
}
int main( void )
{
N two = { NULL , '2' , NULL }, three = { NULL , '3' , NULL };
N four = { NULL , '4' , NULL }, nine = { NULL , '9' , NULL };
N sum = { & two, '+' , & three};
N diff = { & nine, '-' , & four};
N root = { & sum, '*' , & diff};
printf( "%d \n " , eval( & root));
return 0 ;
} A 11 B 10 C 37 D 25
Check answer
Show answer Answer: D. 25
The tree is (2 + 3) * (9 - 4) = 5 * 5 = 25. 37 would come from reading the string without the tree structure as 2 + 3 * 9 - 4.
Question 5 · multiple choice In the worst case, how many comparisons does a search need in a BST with n n n keys?
Check answer
Show answer Answer: A. n n n
If keys are inserted in sorted order, the BST is a chain of height n n n . log 2 n \log_2 n log 2 n holds only for balanced trees (Unit 7).
Question 6 · short answer
Draw the expression tree for (a + b) * c - d / e and write its preorder and postorder traversals.
Show worked answer The last operation is -, so it is the root. Its left subtree is (a + b) * c: * with left child + (children a, b) and right child c. Its right subtree is d / e: / with children d and e. Preorder: - * + a b c / d e. Postorder: a b + c * d e / -.