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:
Exercises
- Write a procedure that uses preorder traversal to store, in each node, the sum of all its ancestors.
- Write a procedure that stores, in each node, the sum of all its children.
Solutions for this page... (Note: I recommend you try to write these on your own, before looking at the solutions, to test your understanding.