The following exercises provide you with the opportunity to practice with binary search trees. The solutions to these exercises are found in the section, ​ Chapter 15 ​ .

  1. Imagine you were to take an empty binary search tree and insert the following sequence of numbers in this order: [1, 5, 9, 2, 4, 10, 6, 3, 8] .

    Draw a diagram showing what the binary search tree would look like. Remember, the numbers are being inserted in the order presented here.

  2. If a well-balanced binary search tree contains 1,000 values, what is the maximum number of steps it would take to search for a value within it?

  3. Write an algorithm that finds the greatest value within a binary search tree.

  4. In the text I demonstrated how to use inorder traversal to print a list of all the book titles. Another way to traverse a tree is known as preorder traversal. Here is the code for it as applied to our book app:

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>def</strong> ​ ​ <strong>traverse_and_print</strong> ​(node):</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>if</strong> ​ node ​ <strong>is</strong> ​ None:</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>print</strong> ​(node.value)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>traverse_and_print(node.leftChild)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>traverse_and_print(node.rightChild)</td></tr></tbody></table>

    For the example tree in the text (the one with Moby Dick and the other book titles), write out the order in which the book titles are printed with preorder traversal. As a reminder, here is the example tree as shown in the diagram .

    images/binary_trees/bst_26.png

  5. There is yet another form of traversal called postorder traversal. Here is the code as applied to our book app:

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>def</strong> ​ ​ <strong>traverse_and_print</strong> ​(node):</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>if</strong> ​ node ​ <strong>is</strong> ​ None:</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>traverse_and_print(node.leftChild)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>traverse_and_print(node.rightChild)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>print</strong> ​(node.value)</td></tr></tbody></table>

    For the example tree in the text (which also appears in the previous exercise), write out the order in which the book titles are printed with postorder traversal.

Copyright © 2020, The Pragmatic Bookshelf.