Practice: Converting BSTs to sorted arrays

The goal of this exercise is to understand how to operation on trees and to understand the correspondence between BSTs and sorted arrays.

1. Set up

Get the starter code from ~tvandrun/Public/cs345/bst2Array-given. Make a new project in Eclipse.

You can find a solution in ~tvandrun/Public/cs345/bst2Array-soln. But don't look there now.

2. The problem

We're using the class BSTNode to stand for a binary search tree. That is, there is no separate class for the BST as a whole. A BST is represented by its root node. Also, this implementation of a BST has no map operations, or any operations at all for that matter. The instance variables, standing for the key and children, are public (but final, and so immutable).

Write the method bst2Array(), which takes a simplified BST, represented by the root node, and returns a sorted array containing the keys. The size of the array should be the number of keys, and when given a null node, the method should return an array of size 0.

Hint: You may want to write one or more recursive helper methods.

Test using BST2ATest.

Bring some evidence that you did the problem to class next time, such as a print out of your code or a photo of the green bar (I'll make an exception to the no-phones-in-class rule for you to show me the picture).


Thomas VanDrunen
Last modified: Fri Mar 15 14:34:20 CDT 2019