我必须编写一个客户端方法,该方法使用给定的代码返回对二进制搜索树中具有最小值的节点中的信息的引用。
以下是ZIP FILE
我必须使用这种方法签名:
Golfer min(BinarySearchTree树)
这是我写的:
Golfer min(BinarySearchTree<Golfer> tree)
{
int treeSize = tree.reset(BinarySearchTree.INORDER);
int numNodes = 0;
for(int count = 1; count <= treeSize; count++)
{
if((tree.getNext(BinarySearchTree.INORDER).compareTo(maxValue)) <= 0)
numNodes = numNodes + 1;
}
return numNodes;
}
答案 0 :(得分:1)
我猜你正在寻找最低分的高尔夫球手
方法1:O(lg(n))时间,因为它沿着树的左侧流动
public Golfer min(BinarySearchTree<Golfer> tree) {
BSTNode<Golfer> node = tree.root;
if (node == null) {
return null;
}
while (node.getLeft() != null) {
node = node.getLeft();
}
return node.getInfo();
}
方法2:O(n)时间,因为它遍历树中的所有元素以创建顺序遍历
public Golfer min2(BinarySearchTree<Golfer> tree) {
int treeSize = tree.reset(BinarySearchTree.INORDER);
if (treeSize <= 0) {
return null;
}
return tree.getNext(BinarySearchTree.INORDER);
}
以下是一些测试上面代码的代码
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("D", 9));
bst.add(new Golfer("E", 3));
Golfer min = new Test().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");
}
}
输出:
min name: E, min score: 3