You are to complete and test the methods in the BSTSet class.
A JUnit test class, BSTSetTest is provided.
Hints, etc.
-
You must use recursion. The public method should call a private method that will need at least 1 more parameter than the public method - namely, a Node parameter. The public method will pass root to this parameter.
-
The private methods that change the tree (remove methods) should return a Node reference that points to the modified tree (or subtree) that was passed to it.
-
The private methods that do NOT change the tree (size methods) typically just return an int.
-
Some public methods return boolean type (isXXX methods). The corresponding private methods may need to return an integer to use to test the condition (depending on what the XXX condition is) as well as whether the condition is true or not.
For example, the public method:
public boolean isBalancedS()
should return true if at every Node, the size of its left subtree is the same as the size of its right subtree.
The private isBalancedS method could in principle return boolean. But at each subtree you need to know 2 things: (1) are the left and right subtrees themselves size balanced and (2) do the left and right subtrees have the same size.
If the private isBalancedS method returned boolean, we would only have the answer for (1). To check (2), we could call the private size method to get the sizes of the left and right subtrees. But this means another recursive descent down into those subtrees!
Solution:
The private isBalancedS should return an int. This value should be the size of the subtree provided the subtree itself is size balanced. But if the subtree is not size balanced, it should return a different value. E.g. -1 will do since the size of a subtree is always >= 0.
The public isBalancedS() method then just checks whether the private method returns -1 or not.
This is much more efficient than calling size(t.left) and size(t.right) at every Node t to check the balance condition in addition to calling isBalancedS(t.left) and isBalanced(t.right) to check that the subtrees are themselves balanced.