Traversal: Linear Data Structures Linked Lists Arrays
Traversal: Linear Data Structures Linked Lists Arrays
Compared to linear data structures like linked lists and one dimensional arrays, which have a
canonical method of traversal, tree structures can be traversed in many different ways. Starting at
the root of a binary tree, there are three main steps that can be performed and the order in which
they are performed defines the traversal type. These steps (in no particular order) are: performing
an action on the current node (referred to as "visiting" the node), traversing to the left child node,
and traversing to the right child node. Thus the process is most easily described
through recursion. The names given for particular style of traversal came from the position of root
element with regard to the left and right nodes. Imagine that the left and right nodes are constant
in space, then the root node could be placed to the left of the left node (pre-order), between the
left and right node (in-order), or to the right of the right node (post-order).
[edit]Depth-first Traversal
To traverse a non-empty binary tree in preorder, perform the following operations recursively at
each node, starting with the root node:
To traverse a non-empty binary tree in inorder (symmetric), perform the following operations
recursively at each node:
To traverse a non-empty binary tree in postorder, perform the following operations recursively at
each node:
[edit]Example
push F
push F B A push F B G
pop F push F B A
pop A pop F
push G B pop A
pop B push A D
pop B push D C
push D C pop B
push D A pop C
pop C push I
pop A push E
pop D pop G
pop D pop E
push E pop A
push E C pop D
pop E push C E
pop C pop B
pop F pop D
pop E push G I H
push G push H
pop G pop H
pop G pop I
push I pop I
push I H pop C
pop I pop G
pop H pop E
push H pop F
pop I pop H
pop H
s