In this assignment, you will be creating a binary search tree (BST). The tree will be storing words (βStringsβ), which you will insert, as well as delete, recursively. You will also be implementing tree traversals, which are different orders in which you recursively visit the items in a tree.
Β
Point Breakdown:
- 10 points: βBinarySearchTreeβ class containing βBSTNodeβ class with constructors, isEmpty()β and βmakeEmpty()β.
- 30 points: βput()β and βcontains()
- 35 points: βdelete()
- 25 points: βinOrder()β, preOrder()β , β βpostOrder()
- 15 points (BONUS): balanceBST()
Β
Introduction to Binary Search Trees
Β
A binary search tree (BST) is an abstract data type, containing operations that enable users to add, remove, and traverse through nodes organized into a tree-like structure. BSTs begin with a node called the root. The root is the first item in your tree, and what your other nodes will be organized around. Below is an example of a BST with integers.
Β
Β
Every node can have up to two children, the left subtree and the right subtree. The data items in the left subtree are all smaller (in our case, earlier in alphabetical order) than the parent. The data items in the right subtree are all larger (in our case, later in alphabetical order) than the parent. There is no duplicate data β every data item is unique (e.g. we donβt store the same word multiple times). More information on BSTs can be found in the textbook starting on page 570.
Β
To test your BST, the main() in TestBST.java creates an instance of your BST and tests it. It makes use of the βprintTreeStructure()β method that weβve provided on BinarySearchTreeβ. This prints out the internal structure of the tree so you can verify your operations are behaving correctly.
Β
Implementing a BST
Β
You will be creating a BST using a BST class called βBinarySearchTreeβ. It implements the interface βBSTInterfaceβ. Along with implementing the methods in the
BSTInterfaceβ, you will need to define a βBSTNodeβ class, which is similar to the βNode class you implemented in previous assignments. βBSTNodesβ will be used to store an item (the textbook calls these keys) which in this assignment are βStringsβ. It will also contain references to its left and right subtrees (which as also βBSTNodesβ). The βBSTNode constructor will initialize the item to a value and the left and right nodes to nullβΒ .β BSTNodeβ should be defined as an βinner class insideβ ofβ β BinarySearchTreeβ β. The fields of BSTNode are:
- String item
- BSTNode left
- BSTNode right
Β
The βBinarySearchTreeβ class itself only has one field, the root of the BST. The constructor for the βBinarySearchTreeβ only has to set the root to βnull.β
Β
We will be using βMyQueueβ to store elements from traversals. That is, instead of preorder, inorder and postorder traversals printing out the elements of the tree, they will each return a βMyQueueβ containing the elements in that order. The βMyQueueβ class and methods will be provided for you, but you may feel free to use your own.
Β
You will be implementing the following methods for your BST:
- publicβ βbooleanβ βisEmptyβ()
Returns true if BST is empty, false otherwise
β publicβ βvoidβ βmakeEmptyβ()
Clears BST so that it is empty
publicβ MyQueue βinOrderβ()
Returns a queue with the elements in-order
- publicβ MyQueue βpreOrderβ()
Returns a queue with the elements in pre-order
- publicβ MyQueue βpostOrderβ()
Returns a queue with the elements in post-order
- publicβ βbooleanβ βcontainsβ(String s)
Returns true if the BST contains the string, otherwise returns false
β publicβ βvoidβ βputβ(String s)
If the string is already in the BST, then put will do nothing. If the string is not inΒ the BST, then put will add the string to the BST.
β publicβ βvoidβ βdeleteβ(String s)
Removes the specified string from the BST, if the string cannot be found, then delete does nothing
Β
Below under each operation are listed page numbers in the book that provide more information on the operation. Additionally, from pages 615-619 you can find source code for a BST, though itβs a more complex implementation than weβre doing. Itβs using Java generics with type variables, is using dictionary-style nodes with keys and values, and builds on other classes we havenβt talked about. But the algorithms in the code on those pages might be helpful.
Β
Implementing pβ ublic β vβ oid β pβ ut(β String s)
Β
Implementing βput(βStringβ βsβ)β will require creating a recursive helper method to assist with searching through the BST to find the appropriate place to put the new node. In your βputβ(βStringβ s)β method, you will need to call βrecursiveInsert()β with the βroot of your BST as one argument and the βString to insert as the other. Set βΒ Β Β Β Β rootβΒ Β Β Β equal toβΒ Β Β Β Β Β Β Β the node returned from βrecursiveInsert()β. The way to think about this is that youβre setting the root equal to the new tree that results from doing the recursive insert.
Β
For more information in the book, pages 602-605 describe inserting into a BST.
Β
protectedβ BSTNode βrecursiveInsertβ(BSTNode node, String s)
Β
You will have two cases to consider: 1) if βnodeβ is βnullβ or 2) when βnodeβ is not nullβ.
- When βnodeβ is βnullβ, this means that youβve come to an empty subtree. This is where you will create the new node. Return a new βBSTNodeβ containing the Stringβ.
- If βnodeβ is not βnull, then you need to compare the β βStringβ argument to the item in the node.
βΒ Β If the βString sβ is alphabetically before βnode.itemβ, then we want to set the left subtree of βnodeβ (βnode.leftβ) equal to recursively inserting βsβ into the left subtree.
βΒ Β Similarly, if the βString sβ is alphabetically after βnode.itemβ, then we want to set the right subtree of βnodeβ (node.rightβΒ )β equal to recursively inserting sβ β into the right subtree.
β Β Β Β In both these cases the recursive call continues searching down the tree looking for the appropriately place to do an insert.
βΒ Β If βString sβ is equal to node.itemβΒ Β Β Β Β Β Β β, we donβt need to do anything. This means the βStringβ is already in the BST. In fact, we donβt even have to explicitly test for this case since weβre not going to do anything other than return the nodeβΒ Β Β Β Β Β Β Β Β .β
- Return the βnodeβ. The way to think about this is that youβre returning the subtree rooted at βnodeβ into which youβve inserted the βStringβ.
Β
Implementing βpublicβ βbooleanβ βcontainsβ(String s)
Β
This method allows you to search through the BST for a specified string, βStringβ s. ItβΒ Β Β Β Β Β Β Β Β Β will return true if the string is stored within the BST, false otherwise. All the work is done by the recursive helper function, recursiveSearch()βΒ Β . All that βΒ Β Β Β Β Β Β Β contains()βΒ Β Β Β Β Β Β does is return the result of calling βrecursiveSearch()β with the root and the βString as arguments.
Β
For more information in the book, pages 600-602 describe searching a BST.
Β
protectedβ βbooleanβ βrecursiveSearchβ(BSTNode node, String s)
This helper function searches the subtree rooted at βnodeβ for the βString sβ, returning trueβ if it finds it, βfalseβ otherwise.
Β
- If βnodeβ is βnullβ we havenβt found the βStringβ. Return βfalseβ.
- If the βitem stored in β βnode is equal to β βs, weβve found the string. Return βΒ βtrueβ.
If βString sβ is alphabetically before βnode.itemβ, return the result of recursively searching the left subtree of βnodeβ.
- If βString sβ is alphabetically after βitemβ, return the result of recursively searching the right subtree of βnodeβ.
Β
Implementing βpublicβ βvoidβ βdeleteβ(String s)
Β
This method searches for StringβΒ Β Β Β sβΒ Β Β Β Β Β Β Β Β and deletes the node in the BST containing it. If itβΒ Β Β Β Β Β Β does not find the specified string, then the method will do nothing.
Β
For more information in the book, pages 605-613 describe deleting items from a BST.
Β
The implementation of βdelete(βStringβ s)β will require the assistance of three helper functions.
- protectedβ BSTNode βrecursiveRemoveβ(BSTNode node, String s)β β given a subtree rooted at βnodeβ and a βString sβ, returns the node that is the root of the new subtree that results from removing βs from the subtree.β
- protectedβ BSTNode βdeleteNodeβ(BSTNode node)β β given a node to remove, returns the new subtree that results from removing that node. This is the method that handles the four cases for deleting nodes: leaf nodes (no children), just a left child, just a right child, and two children (the most complicated case).
- protected String β βgetSmallestβ(BSTNode node)β β returns the alphabetically smallest (first in alphabetical order) βStringβ in the subtree whose root is the nodeβ
All delete()βΒ Β Β Β Β β does is set the root equal to the result of calling βrecursiveRemove() with the root and string as arguments.
Β
protectedβ Node βrecursiveRemoveβ(BSTNode node, String s)
- This function is somewhat similar to the recursive helper functions for βput()β. If the βnodeβ is not equal to βnullβ, then we need to compare βitemβ with the string.
- If the βString s is alphabetically before β βitemβ, then we want to set the left subtree of βnodeβ (βnode.leftβ) equal to recursively removing βs from the left subtree.
βΒ Β If the βString sβ is alphabetically after βnode.itemβ, then we want to set the right subtree of βnodeβ (βnode.rightβ) equal to recursively removing βs from the right subtree.
βΒ Β If βString sβ equals βnode.itemβ, we want to set the βnodeβ equal to the result of calling βdeleteNode()β. This can be thought of as setting βnode equal to the new subtree that results when you delete the root of this subtree.
- If the βnodeβ is βnullβ that means that we never found the string and thereβs nothing we have to do. So we donβt even have to explicitly test for this case. We just need to skip over the tests above if the βnodeβ is βnullβ (which is why thereβs first a test to make sure it isnβt βnullβ).
- Return the βnodeβ. This is the modified subtree after removing the string (or null if the node is null).
Β
protectedβ BSTNode βdeleteNodeβ(BSTNode node) Β deleteNode() handles the four cases of removing a node.β
- Case 1: No children. If both the left and right children are βnullβ this means it is a leaf node and we can just remove it. Set βnodeβ equal to βnullβ.
- Case 2: Just a left child. If thereβs only a left child, then set βnode equal toβ left. The one child is βpromotedβ into being the root of the subtree.β
- Case 3: Just a right child. If thereβs only a right child, then set nodeβ β equal to right. The one child is βpromotedβ into being the root of the subtree.β
- Case 4: Two children. With two children we have to do something more complicated to rearrange the subtree.
- Call βgetSmallest()β on the subtree βrightβ to get the in-order successor. This is the smallest value that is larger than the current node.itemβ (the next item in alphabetical order stored in the tree).
βΒ Β Set βnode.itemβ equal to this in-order successor. The left and right child relationships will still hold: everything to the left will still be alphabetically before the new item and everything to the right will still be alphabetically after the new item (since the new item is the smallest value from the right subtree).
βΒ Β Set βnode.rightβ equal to recursively removing the in-order successor from the right subtree. Since youβve moved this value into the current node, you can now delete the value from the right subtree. When recursiveRemove()β ends up calling βdeleteNode()β again, the in-order successor is guaranteed to be one of the βeasyβ cases (0 or 1 child).
- Return βnodeβ.
Β
protectedβ String βgetSmallestβ(BSTNode node)
- To start the process for finding the smallest string in the subtree rooted at
Β
nodeβ, define a βStringβ variable βsmallestβ and set it equal to βnode.itemβ.
- Now weβll keep on following left branches in the tree (since things to the left are always smaller values), until we canβt go left any more. Then we know weβve found the smallest value.
- While βleftβ is not null
β Β Β Β Β Set βsmallest equal to βΒ Β Β Β Β βnode.left.itemβ.
β Β Β Β Β Β Set βnodeβ equal to βnode.leftβ.
- Return βsmallestβ.
Β
Traversing BSTs
Β
Β
Β
In this portion of the assignment, you will be implementing these methods, which enable you to traverse through your BST:
Β
publicβ MyQueue βinOrderβ()β: Does an in-order traversal to return a queue of strings in-order. This is the strings in alphabetical order.
Β
publicβ MyQueue βpreOrderβ()β: Does a pre-order traversal to return a queue of strings pre-order. This is the order in which youβd want to insert the strings into a new tree to replicate the tree structure.
Β
publicβ MyQueue βpostOrderβ()β: Does a post-order traversal to return a queue of strings post-order. This is the order of strings from the leaves upward, starting from the left and going rightward.
Β
For examples of how these traversals work and further information, you may visit the following links:
Β
https://www.youtube.com/watch?v=gm8DUJJhmY4
Β
https://www.youtube.com/watch?v=5dySuyZf9Qg
Β
https://www.tutorialspoint.com/data_structures_algorithms/tree_traversal.htm
Β
Each of the functions has a recursive helper function:
- voidβ βinOrderRecursiveβ(BSTNode node, MyQueue queue)
- voidβ βpreOrderRecursiveβ(BSTNode node, MyQueue queue)
- void β postOrderRecursiveβ (β BSTNode node, MyQueue queue)
Β
Implementing pβ ublic β MyQueue iβ nOrder(β )
- Create a new βMyQueueβ.
- Call inOrderRecursive() with the rootβ and the new βΒ Β Β Β Β Β Β Β Β Β Β MyQueueβΒ Β Β Β Β Β Β as arguments.β
- Return the βMyQueueβ.
Β
Implementing βpreOrder()β and βpostOrder()β follow the same pattern.
Β
Implementing pβ rotected β vβ oid β iβ nOrderRecursive(β BSTNode node,
MyQueue queue)
- If the node is not null
βΒ Recursively call inOrderRecursive()β on the left subtree.βΒ Β βΒ Β Β Β Β Β Add βnode.itemβ to the queue.
βΒ Β Β Β Β Β Β Recursively call inOrderRecursive()βΒ Β Β on the right subtree.β
Β
Each of the other recursive helpers follow the same pattern. For pre-order, you add to the queue first, then recursively process the left and right subtrees, while for post-order you recursively process the left and right subtrees first, then add the current βnode.itemβ to the queue at the end.
Β
Β
Β
Β
Β
EXTRA CREDIT: Balancing Unbalanced BSTs
Β
Β
Β
As an extra credit method, you can choose toΒ implement βpublicβ βvoid balanceBSTβ()β, which will balance an unbalanced BST. An unbalanced BST contains right and left subtrees with a significantly different numbers of nodes in each subtree. This makes recursive searching operations inefficient.
Β
Implementing βpublicβ βvoidβ βbalanceBSTβ()
To balance a BST, you want to get the values into a sorted array. Then you can recursively divide the array into halves, inserting middle values of each of the recursive halves (kind of like a binary search algorithm) into a new tree.
- Use βinOrder()β to get a queue of the BST values in sorted order.
- Since MyQueueβ doesnβt implement a size operation, youβll need to create aβΒ Β Β temporary queue and βdequeue()β elements into the temporary queue, counting them as you do so.
- Once you have a count, create a βString[]β of this size and copy values from the temporary queue into the array. Β Β Β Β Empty the BST.
- Call the recursive helper βBSTNode βbalanceRecursiveβ(String[] array, intβ first, βintβ last), where β βfirstβ and βlastβ are the initial and final index of the array, setting root equal to the return value.
Β
protectedβ BSTNode βbalanceRecursiveβ(String[] array, βintβ first, βint last)
Think about how binarySearch worked. Youβll want to do something similar, except
that the string at the mid value is what youβll use to make a new BSTNode. The left and right children should be set equal to recursive calls to balanceRecursive(), then youβll want to return the node you created. The base case should return null (this corresponds to a child of a leaf).
Β
Β








