Question: this is in java import java.util.Comparator; public class BinarySearchTree { private BinaryNode root = null; private Comparator comparator; public BinarySearchTree(Comparator comparator) { this.comparator = comparator;
this is in java

import java.util.Comparator;
public class BinarySearchTree { private BinaryNode root = null; private Comparator comparator; public BinarySearchTree(Comparator comparator) { this.comparator = comparator; } public int size() { return root == null ? 0 : root.size(); } private void add(T item, BinaryNode root) { if (this.comparator.compare(item, root.getData()) 0) { // Item is less than root: // add to right subtree if (root.getRight() == null) { // Base case: opening for a right child BinaryNode newNode = new BinaryNode(); newNode.setData(item); root.setRight(newNode); } else { // Recursively add to right subtree add(item, root.getRight()); } } // If elements are equal (duplicate), the item is already in the tree }
public void add(T item) { if (this.root == null) { this.root = new BinaryNode(); this.root.setData(item); } else { add(item, this.root); } }
private boolean contains(T item, BinaryNode root) { if (this.comparator.compare(item, root.getData()) 0) { // Item is less than root: // search in right subtree if (root.getRight() == null) { // Base case: item not found return false; } else { // Recursively search in right subtree return contains(item, root.getRight()); } } else { // Base case: item found return true; } }
public boolean contains(T item) { return this.root == null ? false : contains(item, this.root); } public String toString() { return "[" + (root == null ? "" : root.inOrder(", ")) + "]"; } public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(Comparator.naturalOrder()); for (int i = 0; i
this is binary node class
import java.util.Iterator;
public class BinaryNode
public BinaryNode
public String postOrder(String separator) { return (left == null ? "" : left.postOrder(separator) + separator) + (right == null ? "" : right.postOrder(separator) + separator) + data; }
public String inOrder(String separator) { return (left == null ? "" : left.inOrder(separator) + separator) + data + (right == null ? "" : separator + right.inOrder(separator)); } public Iterator
public T last() { return right == null ? data : right.first(); } public static void main(String[] args) { BinaryNode
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
