The Department of Computer Science & Engineering
 STUART C. SHAPIRO: CSE 116 B

# Trees

Riley Chapter 9

Introduction
Trees are mutable, unbounded collections, with a nonlinear notion of sequence.

A tree may be empty, or may have one or more nodes, one of which is its root. Every node has a mutable, either bounded or unbounded, either ordered or unordered, possibly empty, collection of children. (Having collections of children that are bounded or unbounded, ordered or unordered, is a property of the tree as a whole.) If a node, n has a child m, then n is the parent of m. Every node, other than the root, has exactly one parent. There is exactly one path between the root and any node. A node with no children is called a leaf, or leaf node. The path between the root and a leaf is called a branch. A node with one or more child is called a branch node.

If a node, n is on the path between the root and a node m, then n is an ancestor of n and m is a descendant of n. Nodes with a common parent are siblings. The length of a path between a node and one of its descendants counts the number of nodes on the path less one.

The level of a node is the length of the path from it to the root. The height of a tree is the maximum level of any of its nodes.

Every node is the root of its own subtree, consisting of it and all its descendants.

Recursively, a tree is either empty, or consists of one root node with zero or more subtrees.

For most trees, every node has some value, although some trees have only their leaves having values.

Implementation note for trees
A tree has one or more instance variables for its value(s), and an instance variable for a collection of its children, each of which is a tree.

Examples
• A particular kind of tree known as a trie.

Stores a dictionary.

The characters on any path from the root to any node represents an initial substring of some word.
The characters on any path from the root to a starred node represents a word in the dictionary.

Note it takes 12 nodes to store the 5 words: a, ball, be, car, case
and 9 more nodes to add the additional 6 words: at, are, art, been, bell, cart---less than linear growth of space!

Another way to look at it: every one of the 8 leaves represents a word: at, are, art, ball, been, bell, cart, case.
The other 3 words (a, be, car) are free. Every word that can be formed by an initial substring of another word is stored for free.

• A search tree may not actually be constructed, but represents the search undertaken by some, often recursive, method.

For example the search tree of a reduced Boggle board:

Small Boggle BoardPartial Search Tree
 E A N T