One of the traits that comes with a tree is that it does not have a pre-determined logical ordering of the nodes, unless one is imposed from the outside.
For example, if we have the binary tree:
A
/ \
B C
we could state that the nodes, printed in order, should be ABC
, BAC
, CAB
, BCA
, etc. All would be valid, depending on the criteria that we choose.
It is convenient to describe some of these ordering criteria in a reproducible way. This is similar to how we would describe the traversal of the list from head to tail, a queue from front to back, and a stack from top to bottom. For binary trees, we often consider three traversals: pre-order, in-order, and post-order.
For each of these traversals, there are essentially three operations:
Visiting the node means performing whatever operation we’re trying to do with each node. For example, if we are printing out the items stored in the nodes of the tree, then when we visit a node, we print out its item.
The order of these operations will determine whether we are doing an pre-order, in-order, or post-order traversal.
For the following examples, we will use the following tree:
A
/ \
B C
/ \ / \
D E F G
The order of the operations for a pre-order traversal is:
The resulting pre-order traversal for the example tree is ABDECFG
.
The order of the operations for an in-order traversal is:
The resulting in-order traversal for the example tree is DBEAFCG
.
The order of the operations for a post-order traversal is:
The resulting post-order traversal for the example tree is DEBFGCA
.
For this first warmup exercise, calculate the pre-order, in-order, and post-order traversals for the following tree:
A
/ \
B C
/ \ / \
D E F G
/ \ / \ / \ / \
H I J K L M N O
Type up your traversals in a file called traversals.txt
in your GitHub repository, and do not forget to add
, commit
, and push
the file when you are done.