Chapter 12 Exercises and Problems

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.

转载于:https://www.cnblogs.com/FancyMouse/articles/1070505.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值