Question

Scenario We need to write a method that, given a key as an argument, returns the...

Scenario

We need to write a method that, given a key as an argument, returns the next in order key found in the binary search tree. If the key given as an argument is not found, the method should still return the next in order key. If the binary tree is empty or all the stored keys are smaller than the argument, then the return value should be empty.

For example, using a collection of {10,13,52,67,68,83} stored in the binary search tree:

  • An input of 13 results in 52
  • An input of 67 results in 68
  • An input of 55 results in 67
  • An input of 5 results in 10
  • An input of 83 results in Optional.empty
  • An input of 100 results in Optional.empty
  • Any input on an empty binary tree results in Optional.empty

Both the in order successor and predecessor algorithms have many applications. As an example, think about if you had to keep a scoreboard at some sports event where you only want to show the first three runners. If you keep your data in a binary search tree, you can find the maximum key and then work out the next two predecessor nodes.

The solution needs to have a runtime complexity of O(log n).

Aim

Retrieve the successor of an element when the tree is traversed in inorder.

Prerequisites

  1. Implement the following method, provided in the InOrderSuccessorBinaryTree class that extends the SimpleBinaryTree class.
public Optional<K> inOrderSuccessorKey(K key)

Steps for Completion

  1. Use a non-recursive search operation first to find the first node with a key equal to or less than the input.
  2. Realize that the inorder successor can be in only one of two places, either as a parent of this node or the minimum key on the subtree of the right child of this node (if any).

Task

Use a non-recursive search operation to retrieve the successor element when traversing a tree inorder.

InOrderSuccessorBinaryTree.java

import java.util.Optional;

public class InOrderSuccessorBinaryTree<K,V> extends SimpleBinaryTree<K,V> {
public Optional<K> inOrderSuccessorKey(K key) {
return null;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution

Screenshot

import java.util.Optional;

public class InOrderSuccessorBinaryTree<K, V> extends SimpleBinaryTree<K, V> {
public Optional<K> inOrderSuccessorKey(K key) {
Optional<BinaryTreeNode<K, V>> node = Optional.ofNullable(root);
Optional<K> successor = Optional.empty();
while (node.isPresent() && !node.get().getKey().equals(key)) {
if (((Comparable) node.get().getKey()).compareTo(key) > 0) {
successor = node.map(BinaryTreeNode::getKey);
node = node.flatMap(BinaryTreeNode::getLeft);
} else
node = node.flatMap(BinaryTreeNode::getRight);
}

return node.flatMap(BinaryTreeNode::getRight).map(this::minKey)
.map(Optional::of).orElse(successor);
}
}

--

all the best

Add a comment
Know the answer?
Add Answer to:
Scenario We need to write a method that, given a key as an argument, returns the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • We need to write a method that, given a key as an argument, returns the next...

    We need to write a method that, given a key as an argument, returns the next in order key found in the binary search tree. If the key given as an argument is not found, the method should still return the next in order key. If the binary tree is empty or all the stored keys are smaller than the argument, then the return value should be empty. For example, using a collection of {10,13,52,67,68,83} stored in the binary search...

  • Write a recursive function that returns the minimum key value in a binary search tree of...

    Write a recursive function that returns the minimum key value in a binary search tree of distinct (positive) integers. Return -1 in case the tree is empty. (b) Write a recursive function that returns the predecessor of the key value k in a binary search tree of distinct (positive) integers. This is the key value that precedes k in an inorder traversal of the tree. If k does not exist, or if k has no predecessor, your function should return...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...

    In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {    private BinaryTreeNode root;    /**    * Creates an empty binary tree.    */    public LinkedBinaryTree() {        root = null;    }    /**    * Creates a binary tree from an existing root.    */    public LinkedBinaryTree(BinaryTreeNode root) {        this.root = root;    }    /**    * Creates a binary tree with the specified element...

  • Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate ins...

    Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate insert operation in binary search tree. Please fill in the missing part for the insert method to make the program work. The expected output should be as follows. 20 30 40 50 60 70 80 Part B: Find Lowest Common Ancestor (LCA) of a Binary Search Tree. According to WikiPedia definition , The lowest common ancestor is defined between two nodes v and...

  • In this assignment, you will add several methods to the Binary Search Tree. You should have compl...

    In this assignment, you will add several methods to the Binary Search Tree. You should have completed the following three methods in the lab: public void insert(Key key, Value value) public Value get(Key key) public void inorder(Node root) For this assignment, you will implement the following: public void remove(Node root, Key key) public Key getMin(Node n) public Key getMax(Node n) public int height(Node n) The main method contains the statements to check whether your implementation works. You need to change...

  • I need to do a tree sort method but the treesortMethod is not working /****Binarytree class****\...

    I need to do a tree sort method but the treesortMethod is not working /****Binarytree class****\ package Tree; public class BinaryTree { private TreeNode root; // head of the list    //constructor - create an empty binary tree public BinaryTree() { root = null;    }    //isEmpty() - return true if tree is empty, false otherwise public boolean isEmpty() { return (root == null); }    //deleteTree() - remove all items from tree public void deleteList() { root =...

  • Write a client method that returns a count of the number of nodes in a binary...

    Write a client method that returns a count of the number of nodes in a binary search tree that contain scores less than or equal to a passed-in argument (parameter) value. The method header is: int countLowerScores (BinarySearchTree tree, int maxValue) The BinarySearchTree contains these methods in the picture. public class BinarySearchTreecT> implements BSTInterfacecT> //reference to the root of this BST public BSTNode<T> root; public Comparator<T> comp: IIused for all comparisons public boolean found: / used by remove public BinarYSearchTree()...

  • using java to write,show me the output. please write some common. You CAN NOT use inbuild...

    using java to write,show me the output. please write some common. You CAN NOT use inbuild functions for Tree ADT operations. using code below to finsih public class Main {    public static void main(String[] args) {        BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left .right= new Node(9);...

  • Add printRang method to BST.java that, given a low key value, and high key value, print...

    Add printRang method to BST.java that, given a low key value, and high key value, print all records in a sorted order whose values fall between the two given keys. (Both low key and high key do not have to be a key on the list). BST.java import java.lang.Comparable; /** Binary Search Tree implementation for Dictionary ADT */ class BST<Key extends Comparable<? super Key>, E> implements Dictionary<Key, E> { private BSTNode<Key,E> root; // Root of the BST int nodecount; //...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT