[   ^ to index...   |   <-- previous   |   next -->   ]

Traversals

One of the most fundamental and general operations for a binary tree is traversal. To traverse a binary tree is simply to invoke some operation on every element.

Traversals differ primarily in their orderings. There are three important orderings:

inorder

The most obviously useful traversal: apply some operation to each element in natural sorted order.

void inorder_print(TreeNode *node) { if (node == NULL) { return; } else { inorder_print(node->left); // Visit left cout << node->key << endl; // Visit current inorder_print(node->right); // Visit right } }
preorder

For every node X, "visit" X, and then visit its child subtrees. What would preorder_print look like? How does it differ from an inorder traversal?

postorder

For every node X, Visit the children of X, and then visit X. Define postorder_print.

Write out the inorder, preorder, and postorder traversals of the following tree:

[bst diagram]

Exercises


Solutions for this page... (Note: I recommend you try to write these on your own, before looking at the solutions, to test your understanding.

Last modified: Tue Aug 15 13:44:40 PDT 2000