These lecture notes are based on chapter 9 in ``Data Structures, Algorithms, & Software Principles in C'' by Thomas Standish.
Tree terminology comes from
Some basic definitions
Tree property: There is exactly one path from the root R to each descendant of R (note: there is only one root).
Lots of specialised trees
most important kind - used to model yes/no, on/off, higher/lower, i.e., binary decisions
Recursive Definition: A binary tree is either the empty tree or a node that has left and right subtrees that are binary trees.
Empty trees are represented as boxes in the diagram below (but we will almost always omit the boxes).
In the example tree from the previous diagram, the traversals will visit
Below is an example expression tree.
A typical tree structure in C
typedef struct node {
value_type value;
struct *node left;
struct *node right;
} binary_tree_type;
Assumption is that empty trees will be null pointers.
Preorder traversal code, a recursive technique.
/* preorder traversal of a tree, a recursive technique */
void preorder(binary_tree_type *tree) {
if (tree == NULL) return;
visit(tree);
preorder(tree->left);
preorder(tree->right);
}
Preorder traversal code, a stack technique.
/* preorder traversal of a tree, implemented using a stack */
void preorder(binary_tree_type *tree) {
stack_type *stack;
stack = create_stack();
push(tree, stack);
while (!empty(stack)) {
tree = pop(stack);
visit(tree);
push(tree->left, stack);
push(tree->right, stack);
}
}