Before we examine some more searching techniques, we need to consider some operations on trees - in particular means of traversing trees.
Tree operations
pre-order |
|
in-order |
|
post-order |
|
Parse trees
If we represent the expression: |
then traversing it post-order will produce:
Search Trees
We've seen how to use a heap to maintain a balanced tree for a priority queue. What about a tree used to store information for retrieval (but not removal)? We want to be able to find any item quickly in such a tree based on the value of its key. The search routine on a binary tree:
tree_search(tree T, Key key) { if (T == NULL) return NULL; if (key == T->root) return T->root; else if (key < T->root) return tree_search( T->left, key ); else return tree_search( T->right, key ); }is simple and provides us with a O(log n) searching routine as long as we can keep the tree balanced. However, if we simply add items to a tree, producing an unbalanced tree is easy!
This is what happens if we add the letters |