简体   繁体   中英

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

I have to use this signature of method:

Golfer min(BinarySearchTree tree)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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