Implementing Binary Search Tree Insert operation in Java - java

I have a TreeNode class that represents node of the binary tree.
public class TreeNode {
private static Object key=null;
private static Object value=null;
private TreeNode parent;
private TreeNode left=null;
private TreeNode right=null;
/**
* #return the value
*/
public static Object getValue() {
return value;
}
/**
* #param aValue the value to set
*/
public static void setValue(Object aValue) {
value = aValue;
}
public TreeNode()
{
this(key,value);
}
public TreeNode(Object key,Object value)
{
this.key = key;
this.value = value;
}
/**
* #return the key
*/
public Object getKey() {
return key;
}
/**
* #param key the key to set
*/
public void setKey(Object key) {
this.key = key;
}
/**
* #return the parent
*/
public TreeNode getParent() {
return parent;
}
/**
* #param parent the parent to set
*/
public void setParent(TreeNode parent) {
this.parent = parent;
}
/**
* #return the left
*/
public TreeNode getLeftChild() {
return left;
}
/**
* #param left the left to set
*/
public void setLeftChild(TreeNode left) {
this.left = left;
}
/**
* #return the right
*/
public TreeNode getRightChild() {
return right;
}
/**
* #param right the right to set
*/
public void setRightChild(TreeNode right) {
this.right = right;
}
}
I have a BinarySearchTree class
public class BinarySearchTree implements DataStructures.interfaces.BinarySearchTree {
private int size=0;
private TreeNode root = new TreeNode();
#Override
public void insert(Object key, Object value)
{
insertOperation(key,value,root);
}
private void insertOperation(Object element, Object value, TreeNode node)
{
if(node.getKey() == null) {
node.setKey(element);
node.setValue(value);
}
else
{
if((int) node.getKey() > (int) element)
{
if(node.getLeftChild() != null)
insertOperation(element,value,node.getLeftChild());
else
{
TreeNode child = new TreeNode(element, value);
child.setKey(element);
child.setValue(value);
child.setParent(node);
node.setLeftChild(child);
size++;
}
}
else if((int) node.getKey() <= (int) element)
{
if(node.getRightChild() != null)
insertOperation(element,value,node.getRightChild());
else
{
TreeNode child = new TreeNode(element, value);
child.setKey(element);
child.setValue(value);
child.setParent(node);
node.setRightChild(child);
size++;
}
}
}
}
///more methods
}
The problem is that when I create a child node and set the parent child link. The value of parent node (the node object that I passed) also gets updated and refers to child object.
That is not my intention.
I want to create a chain of treenode objects that can be accessed through the "root" treenode object.
But this is not happening and I do not understand what I am doing wrong.
I know that the problem lies in the logic of this code snippet (not just for inserting on left side but both for inserting left child and right), but I do not understand what exactly.
if(node.getLeftChild() != null)
insertOperation(element,value,node.getLeftChild());
else
{
TreeNode child = new TreeNode(element, value);
child.setKey(element);
child.setValue(value);
child.setParent(node);
node.setLeftChild(child);
size++;
}
All I am telling java to do is if the node in question does not have a left child then create a left child node and set the current node's left side object to the child object.
if the node in question does have a left child then inspect that child and see if the new node should be inserted in left or right by calling the same function for the child of the node in question ... I don't understand why node's (the TreeNode object passed) key gets updated, when i set child's key value.

Why are your key and value static Objects? This means all TreeNodes would share the same key/value. Remove the static keyword and it should work fine.

I don't quite get what you mean by
The problem is that when I create a child node and set the parent child link. The value of parent node (the node object that I passed) also gets updated and refers to child object.
but I did notice one thing that will result an error:
else if((int) node.getKey() <= (int) element)
When node.getKey() == element, it means the bst already has a node with "element" as the key, which should be another special case. Instead you're still traversing through its right child.
Also, it would be nice if you can elaborate your error more clearly...

Related

Adding Nodes to a BinarySearchTree

I ran into problem and can't figure it out why my nodes are not being added to a Binary Tree. I feel like it sets the node and than in the next loop it resets it.
E is a Customer object
T is a LinkedList, list of integers.
I'm not sure if I have to implement the Interface parent also.
I can see in console that it always sets nodes to the right.
Where's the error in my code?
Update:
If I replace in the add method
BinaryNode<E, T> parent = new BinaryNode<>() ;
with
Parent<E, T> parent = this;
Then it seems like its going into while loop and compares, I can see println statements in a console. But then I get an error:
Exception in thread "main" java.lang.ClassCastException:
teama.tree.BinaryNode cannot be cast to teama.tree.Parent
at teama.tree.BinarySearchTree.add(BinarySearchTree.java:32)
at teama.tree.TestBtree.main(TestBtree.java:44)
and this code is highlighted and offering cast it to a BinaryNode:
parent = (Parent<E, T>) node;
If I remove the cast from it
parent = node;
then it highlight the node with the red underline and offers it to cast back.
Why does this happen and how to fix it?
Here's the code:
public class BinaryNode<E, T> {
/** The item associated with this node. */
private E item;
private T item2;
/** The node at the root of the left subtree. */
private BinaryNode<E, T> left;
/** The node at the root of the right subtree. */
private BinaryNode<E, T> right;
public BinaryNode() {
}
/** Put item in a leaf node. */
public BinaryNode(E item, T item2) {
this.item = item;
this.item2 = item2;
public void setChild(int direction, BinaryNode<E, T> child) {
if (direction < 0) {
System.out.println("set Left");
left = child;
} else {
System.out.println("set Right");
right = child;
}
}
Here's BinaryTree class
public class BinarySearchTree <E extends Comparable<E>, T>
implements Parent<E, T>, Set<E> {
{
/** Root node. */
private BinaryNode<E, T> root;
/** A BinarySearchTree is initially empty. */
public BinarySearchTree() {
root = null;
}
Here I had to replace Parent<E,T> with the BinaryNode<E, T>, because nodes below were offered to cast by Eclipse, mismatch type.
public void add(E target, T list) {
// Here I replaced Parent<E> parent = this;
// with BinaryNode<E, T> parent = new BinaryNode<>()
BinaryNode<E, T> parent = new BinaryNode<>() ;
BinaryNode<E, T> node = root;
int comparison = 0;
while (node != null) {
System.out.println("While loop:");
comparison = target.compareTo(node.getItem());
System.out.println("Comparison=" + comparison);
if (comparison < 0) { // Go left
System.out.println("Go Left");
parent = node;
node = node.getLeft();
} else if (comparison == 0) {
// It's already here
return;
} else {
// Go right
System.out.println("Go Right");
parent = node;
node = node.getRight();
}
}
System.out.println("from add method: " + target +" list=" + list);
// BinaryNode<E, T> newNode = new BinaryNode<E, T>(target, list);
// newNode.setChild(comparison, newNode);
parent.setChild(comparison, new BinaryNode<E, T>(target, list));
}
And Parent interface:
public interface Parent<E, T> {
/**
* Return the left child if direction < 0, or the right child
* otherwise.
*/
public BinaryNode<E, T> getChild(int direction);
/**
* Replace the specified child of this parent with the new child.
* If direction < 0, replace the left child. Otherwise, replace
* the right child.
*/
public void setChild(int direction, BinaryNode<E, T> child);
I think I got it resolved. In my BinaryNode class I haven't implemented interface parent, and that's why it was giving me mismatch error type. After I added implements Parent<E> to public class BinaryNode<E, T> it works fine now.

need help in my add node method in my binary tree

I did a code about inserting nodes in a binary tree ... My code is not working because of some reasons in my add method , please look at my comments next to each line .. here is my code where I get problem with ..
public class BinarySearchTree<E extends Comparable<? super E>> {
BinaryNode<E> root;
/**
* Constructs an empty binary searchtree.
*/
public BinarySearchTree() {
}
/**
* Inserts the specified element in the tree if no duplicate exists.
* #param x element to be inserted
* #return true if the the element was inserted
*/
public boolean add(E element) {
BinaryNode newNode = new BinaryNode(element);
if(root==null){
root=newNode;
} if (element==this.element){ // element cannot be resolved or is not a field
return false;
} else {
BinaryNode<E> focus = root;
BinaryNode parent;
while(true) {
parent=focus;
if (element < focus.element) { //The operator < is undefined for the argument type(s) E, Object
focus=focus.left;
if (focus==null) {
parent.left=newNode;
return true;
}
} else {
focus=focus.right;
if (focus==null) {
parent.right=newNode; //
}
return true;
}
}
}
}
static class BinaryNode<E> {
E element;
BinaryNode<E> left;
BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
}
}
}
How to correct my errors?
Is my code suitable? Does it need to be changed?
Thank you
I changed your code where you make a compare element less than focus.element, i have puted element.compareTo(focus.element) < 0, is the way to compare thing without being an integer
public class BinarySearchTree<E extends Comparable<? super E>> {
BinaryNode<E> root;
/**
* Constructs an empty binary searchtree.
*/
public BinarySearchTree() {
}
/**
* Inserts the specified element in the tree if no duplicate exists.
* #param element to be inserted
* #return true if the the element was inserted
*/
public boolean add(E element) {
BinaryNode newNode = new BinaryNode(element);
if(root==null){
root=newNode;
System.out.println("root");
} if (element==root.element){ // element cannot be resolved or is not a field
return false;
} else {
BinaryNode<E> focus = root;
BinaryNode parent;
while(true) {
parent=focus;
if (element.compareTo(focus.element) < 0) { //Here is my change!!! The operator < is undefined for the argument type(s) E, Object
focus=focus.left;
System.out.println("left");
if (focus==null) {
parent.left=newNode;
return true;
}
} else {
focus=focus.right;
System.out.println("right");
if (focus==null) {
parent.right=newNode; //
}
return true;
}
}
}
}
static class BinaryNode<E> {
E element;
BinaryNode<E> left;
BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
}
}
}

Trying to get this linked list started

Second programming class
So we have been tasked with a linked list, building each method from scratch.
Well I started on this day before yesterday and had a null pointer exception, I figured id iron it out later and continued.
Well after cutting my program down to nothing to find the culprit im left with code that SHOULD work as its copied from our lab (that worked).
If you guys think you can figure out why im getting a null pointer exception on my add method id greatly appreciate it and see if im doing the second constructor correctly. If I can get SOME traction on this to get started it would go allot easier but as is I cant even begin.
You will notice allot of blank methods, ill get to them once I can get my constructor + add method working
My code:
import java.util.Collection;
import java.util.Iterator;
/**
* Created by hhhh on 11/2/2014.
*/
public class Lset<R> implements Set151Interface<R> {
private Node head;
private int length;
/**In the first (following) constructor im trying to re use code and call my clear method.
*Should save space and make code look cleaner.
*/
public Lset(){
clear();
}
public Lset(Collection<? extends R> list){
this();
for (R object : list) {
add(object);
}
}
/**
* Copied from Lab7, this add method checks to see if there are more nodes than just the head.
* After the check if false, creates a new node and adds it to the end of the list.
* #param entry
* #return
*/
#Override
public boolean add(R entry) {
Node newNode = new Node(entry);
// empty list is handled differently from a non-empty list
if (head.next == null) {
head = newNode;
} else {
Node lastNode = getNodeAt(length - 1);
lastNode.next = newNode;
}
length++;
return true;
}
#Override
public void clear() {
this.length = 0;
this.head = null;
}
#Override
public boolean contains(Object o) {
return false;
}
#Override
public Iterator<R> iterator() {
return null;
}
#Override
public boolean containsAll(Collection<?> c) {
return false;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public boolean remove(Object o) {
return false;
}
#Override
public boolean addAll(Collection<? extends R> c) {
return false;
}
#Override
public boolean removeAll(Collection<?> c) {
return false;
}
#Override
public boolean retainAll(Collection<?> c) {
return false;
}
#Override
public int size() {
return length;
}
#Override
public Object[] toArray() {
return null;
}
#Override
public <T> T[] toArray(T[] array) {
return null;
}
/**
* Code used in Lab 7, getNodeAt uses the length field and starts at head to traverse array and arrive at the
* position desired.
* #param position
* #return
*/
private Node getNodeAt(int position) {
assert !isEmpty() && (position >= 0) && position < length;
Node cNode = head;
for (int i = 0; i < position; i++)
cNode = cNode.next;
assert cNode != null;
return cNode;
}
public String toString(){
String arrayString = "<";
for(int i = 0; i < length; i++){
String two = getNodeAt(i).toString();
arrayString += two;
if(i <= (length - 2)){
two = ", ";
arrayString += two;
}
}
arrayString += ">";
return arrayString;
}
//TODO comment better
public class Node {
/** Reference to the data */
public R data;
/** Reference to the next node is in the list */
public Node next;
/**
* Sets the data for this node.
* #param data data to be carried by this node.
*/
public Node(R data) {
this.data = data;
this.next = null;
}
/**
* Sets the data for the node and assigns the next node in the list.
* #param data data to be carried by this node.
* #param nextNode next node in the list.
*/
public Node(R data, Node nextNode) {
this.data = data;
this.next = nextNode;
}
/**
* Returns just the data portion of the node.
* #return The data portion of the node.
*/
public R getData() {
return this.data;
}
/**
* Modified just the data portion of the node.
* #param data new data to be contained within the node.
*/
public void setData(R data) {
this.data = data;
}
/**
* What node does this node point to.
* #return the node that this node points to or null if it does not
* point anywhere.
*/
public Node getNextNode() {
return this.next;
}
/**
* Change the node that this node points to.
* #param nextNode a new node for this node to point to.
*/
public void setNextNode(Node nextNode) {
this.next = nextNode;
}
/**
* Display the state of just the data portion of the node.
*/
public String toString() {
return this.data.toString();
}
}
}
This is the method in main thats killing it
private void testConstruction() {
System.out.println("\nTesting Constructor");
System.out.print("----------------------------------------");
System.out.println("----------------------------------------");
Set151Interface s = makeSet();
//added
s.add("Butterfinger");
test(s.size() == 0,
"size() should return 0: " + s.size());
test(s.toString().equals("<>"),
"toString returns \"<>\": " + s.toString());
ArrayList<String> temp = new ArrayList<String>();
temp.add("Butterfinger");
temp.add("Milky Way");
temp.add("Kit Kat");
temp.add("Three Muskateers");
Set151Interface s3 = makeSet(temp);
test(s3.size() == 4,
"size should return 4: " + s3.size());
test(s3.toString().equals("<Butterfinger, Milky Way, Kit Kat, Three Muskateers>"),
"toString should return\n "+
"\"<Butterfinger, Milky Way, Kit Kat, Three Muskateers>\":\n "
+ s3.toString());
}
as soon as butterfinger attempts to get added I get null pointer exception pointing to this line
if (head.next == null) {
You just declared private Node head; and it doesnt takes any value assigned . so the compiler throws NPE
Thanks for the help guys, I figured it out :).
On day one I had edited my driver (and forgot) once I re copied the driver everything works (so far) thanks again guys!

Inserting a node in BST

I am trying to insert nodes in my custom BST.The first time the insertData method is called , the new node is correctly inserted as the root.The problem is occuring in the second and subsequent calls.
Below is My code :
1.The Node Class =
package ishan.trees.tree;
class Node implements Comparable<Node> {
private int data;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
private Node leftChild;
private Node rightChild;
public Node(int data,Node leftChild,Node rightChild)
{
this.data=data;
this.leftChild=leftChild;
this.rightChild=rightChild;
}
#Override
public int compareTo(Node o) {
if(o.getData() > this.data)
return -1;
if(o.getData() < this.data)
return 1;
return 0;
}
}
The Tree Class =
package ishan.trees.tree;
public class Tree {
private Node root=null;
public Node getRoot() {
return root;
}
public void insertData(int data)
{
Node node=new Node(data,null,null);
insert(node,this.root);
}
private Node insert(Comparable<Node> node,Node root1)
{
if(root1==null)
{//insert as first element ie root
this.root=new Node(((Node)node).getData(),null,null);
}
else if(node.compareTo(root1) <0)
{
root1.setLeftChild(insert(node,root1.getLeftChild()));
}
else if(node.compareTo(root1) >0)
{
root1.setLeftChild(insert(node,root1.getRightChild()));
}
return root1;
}
}
3.Main Class =
package ishan.trees.usage;
import ishan.trees.tree.Tree;
public class Usuage {
public static void main(String a[])
{
Tree tree=new Tree();
tree.insertData(10); //---------1
tree.insertData(15); //---------2
tree.insertData(9); //---------3
tree.insertData(4); //---------4
}
}
when i debug the second call it is something like this:
insertData(15){
insert(15,10)
}
which makes a call to the insert method as ---->
insert(15,null)
I get this null every time and this results in the current node replacing the root node.
I cant figure out why during the call , the root1 reference is null and not pointing to my root?
More Info :
Its during the call from insertData() to insert() . say During my second call to insertData(15) , i make a call to insert(15,this.root) -->insert(node,root1) . but this root1 reference turns out to be null.but when i inspect this.root it is referring to the correct root node..
Thanks!
Alright here is dry run for your code,
Inserting 10.
When you insert first element, this API insert creates a new root for you as per your code and sets it value to 10,
now second insertion makes it interesting, watch what happenes
StackTrace
insertData(15);
insert(node,root) // here root is your actuall root, originally initialized when u inserted first
// it goes to last else if inside insert api
root1.setRightChild(insert(node,root1.getRightChild())); // see now, this apis actually calls insert again, coz new node value was greater then root value
// this is how next stack trace will look like, as root right child was null
insert(node,null); // observer second argument is null again
now as per your Insert code will end up creating root again(root1 argument is null, first condition is executed), discarding previously defined root. this is what is causing your issue you are overriding your root again and again.
After inserting first node i.e root, left and right node will be null. Next time while inserting left or right child node you are not checking that condition.
private Node insert(Comparable<Node> node,Node root1)
{
if(root1==null)
{//insert as first element ie root
this.root=new Node(((Node)node).getData(),null,null);
}
else if(node.compareTo(root1) <0)
{
if(root1.getLeftChild()==null)
root1.setLeftChild(node);
else
root1.setLeftChild(insert(node,root1.getLeftChild()));
}
else if(node.compareTo(root1) >0)
{
if(root1.getRightChild()==null)
root1.setRightChild(node);
else
root1.setRightChild(insert(node,root1.getRightChild()));
}
return root1;
}

BinaryTreeLUT , tree deletion

I have the following binary search tree as below, and am trying to delete a node using the method illustrated in this wiki
http://en.wikipedia.org/wiki/Binary_search_tree#Deletion
The main idea is to modify lrMerge (method in below code) when both subtrees are present. Then the node to be deleted is replaced by the rightmost node in the left tree (which itself is deleted). There is a test file at the end of the code below. I tried to change IrMerge to be like the wiki deletion code - but have not been succesful.
class KeyNotFoundInTableException extends Exception {
}
public class BinaryTreeLUT {
/**
* The member class Key is used for the indexing keys of the LUT. It
* is a String with basic comparative methods added.
*/
protected class Key {
public Key(String s) {
kString = s;
}
public boolean equals(Key k) {
return kString.equals(k.toString());
}
public boolean lessThan(Key k) {
return (kString.compareTo(k.toString()) < 0);
}
public boolean greaterThan(Key k) {
return (kString.compareTo(k.toString()) > 0);
}
public String toString() {
return kString;
}
private String kString;
}
/**
* The member class Entry encapsulates an entry of the LUT and contains
* a {key, value} pair.
*/
protected class Entry {
public Entry(Key k, Object v) {
key = k;
value = v;
}
protected Key key;
protected Object value;
}
/**
* The member class BSTreeNode encapsulates node of the binary search
* tree, which contains a LUT entry and links to left and right
* subtrees.
*/
protected class BSTreeNode {
public BSTreeNode(Entry e) {
kvPair = e;
left = null;
right = null;
}
public BSTreeNode(Entry e, BSTreeNode l, BSTreeNode r) {
kvPair = e;
left = l;
right = r;
}
protected Entry kvPair;
protected BSTreeNode left;
protected BSTreeNode right;
}
//Single protected data member - the LUT is stored in a sequence.
protected BSTreeNode root;
/**
* Default constructor - no need to specify capacity of LUT.
*/
public BinaryTreeLUT() {
root = null;
}
/**
* Inserts a new key-value pair into the look-up table.
*/
public void insert(String key, Object value) {
BSTreeNode newNode = new BSTreeNode(new Entry(new Key(key), value));
addToTree(newNode, root);
}
/**
* Removes the key-value pair with the specified key from the look-up
* table.
*/
public void remove(String key) throws KeyNotFoundInTableException {
Key searchKey = new Key(key);
removeFromTree(searchKey, root);
}
/**
* Retrieves the key-value pair with the specified key from the look-up
* table.
*/
public Object retrieve(String key) throws KeyNotFoundInTableException {
Key searchKey = new Key(key);
BSTreeNode treeNode = getFromTree(searchKey, root);
return treeNode.kvPair.value;
}
/**
* Updates the key-value pair with the specified key with the new
* specified value.
*/
public void update(String key, Object value) throws KeyNotFoundInTableException {
Key searchKey = new Key(key);
BSTreeNode treeNode = getFromTree(searchKey, root);
treeNode.kvPair.value = value;
}
/**
* Returns a string listing all the key-entry pairs in the LUT
*/
public String toString() {
return treeString(root);
}
//protected methods implementing recursive operations on the tree.
/**
* Adds newNode to the tree rooted at curNode recursively.
*/
protected void addToTree(BSTreeNode newNode, BSTreeNode curNode) {
//Special case for empty tree.
if(curNode == null) {
root = newNode;
}
//General case: recurse left or right depending on comparison.
else if(curNode.kvPair.key.lessThan(newNode.kvPair.key)) {
if(curNode.left == null) {
curNode.left = newNode;
}
else {
addToTree(newNode, curNode.left);
}
}
else {
if(curNode.right == null) {
curNode.right = newNode;
}
else {
addToTree(newNode, curNode.right);
}
}
}
/**
* Returns the node containing k from the tree rooted at node.
*/
protected BSTreeNode getFromTree(Key k, BSTreeNode node) throws KeyNotFoundInTableException {
if(node == null) {
throw new KeyNotFoundInTableException();
}
else if(node.kvPair.key.equals(k)) {
return node;
}
else if(node.kvPair.key.lessThan(k)) {
return getFromTree(k, node.left);
}
else {
return getFromTree(k, node.right);
}
}
/**
* Removes the node containing k from the tree rooted at node.
*/
protected void removeFromTree(Key k, BSTreeNode node) throws KeyNotFoundInTableException {
//Special case for empty tree.
if(node == null) {
throw new KeyNotFoundInTableException();
}
//Special case when deleting the root node.
else if(root.kvPair.key.equals(k)) {
root = lrMerge(root);
}
//If the key at the current node is less than
//the search key, go to the left subtree.
else if(node.kvPair.key.lessThan(k)) {
//If the left subtree is empty, the tree cannot contain
//the search key.
if(node.left == null) {
throw new KeyNotFoundInTableException();
}
//If this is the parent of the node to be removed, do
//the removal.
if(node.left.kvPair.key.equals(k)) {
node.left = lrMerge(node.left);
}
//Otherwise, recurse down another level.
else {
removeFromTree(k, node.left);
}
}
//Otherwise go to the right subtree.
else {
//If the right subtree is empty, the tree cannot contain
//the search key.
if(node.right == null) {
throw new KeyNotFoundInTableException();
}
//If this is the parent of the node to be removed, do
//the removal.
if(node.right.kvPair.key.equals(k)) {
node.right = lrMerge(node.right);
}
//Otherwise, recurse down another level.
else {
removeFromTree(k, node.right);
}
}
}
/**
* Merges the two subtrees of node prior to removal of
* the node from the tree.
*/
protected BSTreeNode lrMerge(BSTreeNode node) {
BSTreeNode mergedTrees = null;
//First two cases occur when one or both
//subtrees of the node to be deleted are empty.
if(node.left == null) {
mergedTrees = node.right;
}
else if(node.right == null) {
mergedTrees = node.left;
}
//Otherwise, merge the left and right subtrees
//and link the merged structure to the current
//node.
else {
addToTree(node.right, node.left);
mergedTrees = node.left;
}
return mergedTrees;
}
/**
* Uses in order tree traversal to construct a string containing all the
* key value pairs in the binary search tree.
*/
protected String treeString(BSTreeNode node) {
if(node == null) {
return "";
}
Entry lutEntry = node.kvPair;
String thisNode = "";
thisNode = lutEntry.key.toString();
thisNode += ":";
thisNode += lutEntry.value;
thisNode += ", ";
return treeString(node.left) + treeString(node.right) + thisNode;
}
}
The test file is here:
BinaryTreeLUTTest.java:
public class BinaryTreeLUTTest {
public static void main(String[] args) {
try {
BinaryTreeLUT myLUT = new BinaryTreeLUT();
myLUT.insert("Priscilla", new Integer(41));
myLUT.insert("Travis", new Integer(34));
myLUT.insert("Samuel", new Integer(28));
myLUT.insert("Helena", new Integer(39));
myLUT.insert("Andrew", new Integer(14));
myLUT.insert("Kay", new Integer(24));
myLUT.insert("John", new Integer(67));
System.out.println(myLUT);
myLUT.remove("Helena");
System.out.println(myLUT);
myLUT.remove("John");
System.out.println(myLUT);
myLUT.remove("Travis");
System.out.println(myLUT);
myLUT.remove("Samuel");
System.out.println(myLUT);
myLUT.remove("Andrew");
System.out.println(myLUT);
} catch (Exception e) {
System.out.println(e);
}
}
}

Categories