Lecture 10: Trees. 3/4

A tree is a structure that starts at a single point called the root and then branches out from there. Going out from the root, different branches never join back up together.

In computer science, trees are usually drawn, and described, with the root on top, branching downward. Sometimes (for convenience of drawing, or when branching represents movement in time) they are drawn with the root on the left, branching toward the right. Rarely are they drawn like a forest tree, with the root at the bottom.

Node A is an ancestor of node D, and D is a descendant of A if you can get from D to A following parent arcs. That is, A is D's parent; or D's parent's parent; or D's parent's parent's parent; etc.

Trees in computer science

Trees in the outside world


The depth of node N is the number of steps from the root to N. The root has depth 0, its children have depth 1, etc.

The height of the tree is the greatest depth of any node in the tree.

The subtree under node N is the tree that has root N and that contains all the descendants of N.

The branching factor at node N is the number of children of N. The maximal branching factor for the tree is the maximum branching factor at any node.

Tree variations

Structural variants

Implementational variants

First implementation

Maximum number of children. Keep the children of node N as an array list.


Second implementation

Arbitrarily many children (singly linked list). Pointers up and down tree. No distinction between leaves and internal nodes.


Tree traversals

Preorder: List the label at the node, then recursively preorder all the subtrees.
Mammal, Primate, Human, Gorilla, Rodent, Squirrel, Rat, Carnivore, Skunk, Dog, Cat.

Postorder: Recursively postorder all the subtrees, then list the label at the node.
Human, Gorilla, Primate, Squirrel, Rat, Rodent, Skunk, Dog, Cat, Carnivore, Mammal.


Binary tree

An internal node has at most two children: the left child and the right child. In this implementation, there are only downward pointers, no upward pointers.


Inorder: Recursively inorder the left subtree, then list the label at the node, then recursively inorder the right subtree.
#LLL, #LL, #LLR, #L, #LRL, #LR, #LRR, #, #RLL, #RL, #RLR, #R, #RRL, #RR, #RRR

Expression trees

Correspond to arithmetic expression. The label in an internal node is an operator, which operates on the expressions in the left and right subtrees. The label on a leaf is a number. To simplify programming, we put that in a separate field called value.

Evaluate a tree N: