Searching for a Minimum Key in a Binary Tree

The aim is to implement a method in Java to search for the minimum key in a binary tree.

Perform the following steps:

  1. Add a method to the binary tree implementation with the following signature:
 public Optional<K> minKey()  
  1. The method needs to find the minimum key in the tree and return it. If the tree is empty, it should return an empty optional.
  2. Finding the minimum in a binary search tree requires us to always follow the left child node until we reach a node with no left child pointer. The following code demonstrates this:
public Optional<K> minKey() {
return Optional.ofNullable(root).map(this::minKey);
}
private K minKey(BinaryTreeNode<K, V> node) {
return node.getLeft().map(this::minKey).orElse(node.getKey());
}
Snippet 3.12: Minimum key operation. Source class name: SimpleBinaryTree.

Go to https://goo.gl/YbZz6i to access this code.

In this section, we have introduced binary search trees and explored how they can be used to organize key value pairs. We also saw how binary search trees can be used for simple range queries, such as finding the maximum and minimum keys. In the next section, we learn about all the different ways we can traverse a binary search tree.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.7.208