Topic: | Trees (Overview, BST) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 28, 2009 |
A set of nodes with zero, one, or more references to other nodes, where each node only has one other node referencing it:
In a binary tree, each node has no more than two children, usually referred to as the right and left children.
// 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);
}
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).
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.
Quick questions:
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);
}