简体   繁体   English

如何在二叉搜索树中找到最小值?

[英]How to find smallest value in a binary search tree?

I have to write a client method that returns a reference to the information in the node with the smallest value in a binary search tree using the codes given. 我必须编写一个客户端方法,使用给定的代码返回对二进制搜索树中具有最小值的节点中信息的引用。

Here is the ZIP FILE 这是ZIP文件

I have to use this signature of method: 我必须使用以下方法签名:

Golfer min(BinarySearchTree tree) 高尔夫球手(BinarySearchTree树)

Here's what I have written: 这是我写的:

   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;     
   }

I am guessing you are looking for the Golfer with the minimum score 我猜您正在寻找分数最低的高尔夫球手

Method 1: O(lg(n)) time because it runs down the left side of the tree 方法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();
}


Method 2: O(n) time because it runs through all the elements in the tree to create an in order traversal 方法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);
}

Here is some code to test the code above 这是一些代码来测试上面的代码

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");
    }
}

Output: 输出:

min name: E, min score: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM