For Exercises 1 and 2 we assume the client is working with a
For Exercises 1 and 2 we assume the client is working with a tree of Golfer objects. The Golfer class is included below:
1.) Write a client method that returns a reference to the information in the node with the \"smallest\" value in a binary search tree. The signature of the method is
Golfer min (BinarySearchTree<Golfer> tree)
2.) Write a client method that returns a reference to the information in the node with the \"largest\" value in a binary search tree. The signature of the method is
Golfer min (BinarySearchTree<Golfer> tree)
//----------------------------------------------------------------------
// Golfer.java by Dale/Joyce/Weems Chapter 6
//
// Supports golfer objects having a name and a score.
// Allows golfers to be compared based on their scores.
//----------------------------------------------------------------------
package support;
public class Golfer implements Comparable<Golfer>
{
protected String name;
protected int score;
public Golfer(String name, int score)
{
this.name = name;
this.score = score;
}
public String getName()
{
return name;
}
public int getScore()
{
return score;
}
public int compareTo(Golfer other)
{
if (this.score < other.score)
return -1;
else
if (this.score == other.score)
return 0;
else
return +1;
}
public String toString()
{
return (score + \": \" + name);
}
}
Solution
public class TestMinGolfer {
public static void main(String[] args) {
BinarySearchTree<Golfer> bst = new BinarySearchTree<Golfer>();
bst.add(new Golfer(\"A\", 10));
bst.add(new Golfer(\"B\", 12));
bst.add(new Golfer(\"C\", 8));
bst.add(new Golfer(\"E\", 3));
bst.add(new Golfer(\"D\", 9));
Golfer min = min(bst);
// Golfer min = new Test().min2(bst);
if (min != null) {
System.out.println(\"min name: \" + min.name + \", min score: \"
+ min.score);
} else {
System.out.println(\"Empty tree\");
}
}
public static Golfer min(BinarySearchTree<Golfer> tree) {
int treeSize = tree.reset(BinarySearchTree.INORDER);
if (treeSize <= 0) {
return null;
}
return tree.getNext(BinarySearchTree.INORDER);
}
}
OUTPUT:
min name: E, min score: 3

