Close
Register
Close Window

BM40A1500 Data Structures and Algorithms

Chapter 4 Recursion and Binary Trees

Show Source |    | About   «  4.5. Binary Search Trees   ::   Contents   ::   4.7. Dictionary Implementation Using a BST  »

4.6. Binary Tree Traversals

Often we wish to process a binary tree by “visiting” each of its nodes, each time performing a specific action such as printing the contents of the node. Any process for visiting all of the nodes in some order is called a traversal. Any traversal that lists every node in the tree exactly once is called an enumeration of the tree’s nodes. Some applications do not require that the nodes be visited in any particular order as long as each node is visited precisely once. For other applications, nodes must be visited in an order that preserves some relationship.

4.6.1. Preorder Traversal

For example, we might wish to make sure that we visit any given node before we visit its children. This is called a preorder traversal.

Figure 4.6.1: A binary tree for traversal examples.

Example 4.6.1

The preorder enumeration for the tree of Figure 4.6.1 is A B D C E G F H I.

The first node printed is the root. Then all nodes of the left subtree are printed (in preorder) before any node of the right subtree.

Settings

Proficient Saving... Error Saving
Server Error
Resubmit

4.6.2. Postorder Traversal

Alternatively, we might wish to visit each node only after we visit its children (and their subtrees). For example, this would be necessary if we wish to return all nodes in the tree to free store. We would like to delete the children of a node before deleting the node itself. But to do that requires that the children’s children be deleted first, and so on. This is called a postorder traversal.

Example 4.6.2

The postorder enumeration for the tree of Figure 4.6.1 is D B G E H I F C A.

Settings

Proficient Saving... Error Saving
Server Error
Resubmit

4.6.3. Inorder Traversal

An inorder traversal first visits the left child (including its entire subtree), then visits the node, and finally visits the right child (including its entire subtree). The binary search tree makes use of this traversal to print all nodes in ascending order of value.

Example 4.6.3

The inorder enumeration for the tree of Figure 4.6.1 is B D A G E C H F I.

Settings

Proficient Saving... Error Saving
Server Error
Resubmit

   «  4.5. Binary Search Trees   ::   Contents   ::   4.7. Dictionary Implementation Using a BST  »

nsf
Close Window