CSE 40872 Lecture 012

Topic:Trees (Overview, BST)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 28, 2009

Trees

A set of nodes with zero, one, or more references to other nodes, where each node only has one other node referencing it:

http://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Binary_search_tree.svg/200px-Binary_search_tree.svg.png

Terminology

Parent
Node that points to other nodes is the parent of those nodes.
Child
Node is the child of any node that points to it.
Leaves
Nodes that do not have any children.

Binary Trees

In a binary tree, each node has no more than two children, usually referred to as the right and left children.

http://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Binary_tree.svg/180px-Binary_tree.svg.png

Implementation

// Binary tree of integers
struct IntNode {
    int value;
    struct IntNode *left;
    struct IntNode *right;
};

static struct IntNode *
create_node(const int v) {
    struct IntNode *n = malloc(sizeof(IntNode));
    n->left  = n->right = NULL;
    n->value = v;
    return (n);
}

Binary Search Trees

Trees are often used to store for sorted or ordered data. Consider the STL map data structure. The most common method is using a Binary Search Tree (BST).

BST Rules

1. Left subtree of a node only contains nodes with keys less than the node's key.

2. Right subtree of a node only contains nodes with keys greater than the node's key.

  1. Both the left and right subtrees must also be binary search trees.

BST Properties

Quick questions:

  1. Which node is the smallest, largest in a BST?
  2. How would you print the nodes in order?

Insertion Implementation

static void
insert_node(struct IntNode *n, int v)
{
    if (n == NULL)
        n = create_node(v);
    else if (v < n->key)
        insert_node(n->left, v);
    else
        insert_node(n->right, v);
}