Fancy Mouse
- -|||
Exercises
12.1-3 Give a nonrecursive algorithm that performs an inorder tree walk.
Here I give a solution that uses no stack but assumes that two pointers can be tested for equality.
InorderTraverse(T)
{
    Node
*p = T.root, *q = T.root;
   
while(p->left != NIL) p = p->left; //p is now the first node to be visited
    while(q->right != NIL) q = q->right; //q is the last
    while(p != q)
   
{
        p
->Print;
        p
= p->parent;
       
if(p->right != NIL)
       
{
            p
= p->right;
           
while(p->left != NIL) p = p->left;
        }

    }

    q
->Print;
}

This does not seem to be elegant, but it does perform a inorder tree walk in Θ(n) time, because any tree edge is visited twice and there're n-1 edges in an n-node tree in all.
Note that the structure of the traverse can also be applied to ex 12.2-7

12.3-5 Is the operation of deletion "commutative" in the sense that deleting x and then y from a binary search tree leaves the same tree as deleting y and then x? Argue why it is or give a counterexample.
Deletion is commutative for a ordinary binary search tree. We'll simply observe the situation when TREE-DELETE may pick the predecessor of a node.
Recall that the deletion operation only requires the change of the node itself, and additionally the node's predecessor (if necessary). So if x is not y's predecessor and vice versa, the two operations are independent and the different deletion order won't make a different tree.
If x is y's predecessor, then x is a leaf node. Deleting x is simple, and deleting y will replace y with x's parent. If y is deleted first, x will replace y. Then the deletion of x afterwards will substitute x's new predecessor (which is also x's original parent) for x. This leads to the identical tree.

Problems
12.3 Average node depth in a randomly built binary search tree
f. Describe an implementation of quicksort in which the comparisons to sort a set of elements are exactly the same as the comparisons to insert the elements into a binary search tree. (The order in which comparisons are made may differ, but the same comparisons must be made.)
Any quicksort whose partition is based on the comparison between the candidate and the pivot satisfies the requirement. The pivot is the root of the subtree, and the comparison between the candidate and the pivot is equivalent to the process that the candidate goes down the root (left or right).
And of course, an optimization of using insertion sort in a small scale input is not allowed.
posted on 2008-02-16 11:27  Fancy Mouse  阅读(1519)  评论(0编辑  收藏  举报