| www.delorie.com/gnu/docs/avl/libavl_50.html | search |
![]() Buy GNU books! | |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Now we can work on improving the convenience of our traversal function. But, first, perhaps it's worthwhile to demonstrate how inconvenient it really can be to use walk(), regardless of how it's implemented internally.
Suppose that we have a BST of character strings and, for whatever reason, want to know the total length of all the strings in it. We could do it like this using walk():
With the functions first_item() and next_item() that we'll write in this section, we can rewrite these functions as the single function below:
You're free to make your own assessment, of course, but many programmers prefer the latter because of its greater brevity and fewer "unsafe" conversions to and from void pointers.
Now to actually write the code. Our task is to modify traverse_iterative() so that, instead of calling action, it returns node->bst_data. But first, some infrastructure. We define a structure to contain the state of the traversal, equivalent to the relevant argument and local variables in traverse_iterative(). To emphasize that this is not our final version of this structure or the related code, we will call it struct traverser, without any name prefix:
Function first_item() just initializes a struct traverser and returns the first item in the tree, deferring most of its work to next_item():
Function next_item() is, for the most part, a simple modification of traverse_iterative():
/* Returns the next data item in inorder |
See also: [ Knuth 1997], algorithm 2.3.1T; [ Knuth 1992], p. 50--54, section "Recursion Elimination" within article "Structured Programming with go to statements".
Exercises:
1. Make next_item() reliable by providing alternate code to execute on stack overflow. This code will work by calling bst_balance() to "balance" the tree, reducing its height such that it can be traversed with the small stack that we use. We will develop bst_balance() later. For now, consider it a "black box" that simply needs to be invoked with the tree to balance as an argument. Don't forget to adjust the traverser structure so that later calls will work properly, too. [answer]
2. Without modifying next_item() or first_item(), can a function prev_item() be written that will move to and return the previous item in the tree in inorder? [answer]
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| webmaster donations bookstore | delorie software privacy |
| Copyright © 2003 by The Free Software Foundation | Updated Jun 2003 |