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;
}
}
}
Related
I am trying to implement addFirst to a singly linked list in Java. For some reason my implementation does not print out the linked list correctly. I prdict the problem is in either the addFirst, get, or toString methods. Any help would be greatly appreciated. Thanks in advance.
I predict that i am not creating the nodes correctly and I would appreciate an extra eye to spot what I am missing
import java.util.Iterator;
/**
* A basic singly linked list implementation.
*/
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
E value;
Node<E> next;
public Node(E e)
{
e = value;
next = null;
}
}
//----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
private Node<E> head = null; // head node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
*
* #return number of elements in the linked list
*/
public int size() {
return size;
}
/**
* Tests whether the linked list is empty.
*
* #return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
#Override
public E get(int i) throws IndexOutOfBoundsException {
if(i>this.size()) {
int count = 0;
Node<E> a = head;
while(count != i) {
count ++;
System.out.println(a.value);
a = a.next;
}
}
return null;
}
#Override
public E set(int i, E e) throws IndexOutOfBoundsException {
return null;
}
#Override
public void add(int i, E e) throws IndexOutOfBoundsException {
}
#Override
public E remove(int i) throws IndexOutOfBoundsException {
return null;
}
/**
* Returns (but does not remove) the first element of the list
*
* #return element at the front of the list (or null if empty)
*/
public E first() {
// TODO
return null;
}
/**
* Returns the last node of the list
*
* #return last node of the list (or null if empty)
*/
public Node<E> getLast() {
// TODO
return null;
}
/**
* Returns (but does not remove) the last element of the list.
*
* #return element at the end of the list (or null if empty)
*/
public E last() {
// TODO
return null;
}
// update methods
/**
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
if(this.size() == 0) {
Node<E> first = new Node<E>(e);
this.size++;
this.head = first;
} else {
Node<E> first = new Node<E>(e);
first.next = this.head;
this.head = first;
this.size++;
}
}
/**
* Adds an element to the end of the list.
*
* #param e the new element to add
*/
public void addLast(E e) {
// TODO
}
/**
* Removes and returns the first element of the list.
*
* #return the removed element (or null if empty)
*/
public E removeFirst() {
// TODO
return null;
}
#SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
// TODO
return false; // if we reach this, everything matched successfully
}
#SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// TODO
return null;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
* #return
*/
public String toString() {
for(int i=0;i<this.size();i++) {
System.out.println(this.get(i));
}
return "end of Linked List";
}
private class SinglyLinkedListIterator<E> implements Iterator<E> {
#Override
public boolean hasNext() {
// TODO
return false;
}
#Override
public E next() {
// TODO
return null;
}
}
public Iterator<E> iterator() {
return new SinglyLinkedListIterator<E>();
}
public static void main(String[] args) {
//ArrayList<String> all;
//LinkedList<String> ll;
/*SinglyLinkedList<String> sll = new SinglyLinkedList<String>();
String[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
for (String s : alphabet) {
sll.addFirst(s);
sll.addLast(s);
}
System.out.println(sll.toString());
for (String s : sll) {
System.out.print(s + ", ");
}
*/
SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
ll.addFirst(1);
ll.addFirst(3);
System.out.println(ll);
}
}
You have a bug in the constructor of the Node class:
public Node(E e)
{
e = value;
should be
public Node(E e)
{
value = e;
Also, assuming this is the method that you've added:
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
if(this.size() == 0) {
Node<E> first = new Node<E>(e);
this.size++;
this.head = first;
} else {
Node<E> first = new Node<E>(e);
first.next = this.head;
this.head = first;
this.size++;
}
}
You don't really have to differentiate between the cases when the list is empty or otherwise.
You could:
Create a new node
Chain the current head to this newly created node
Set the head to the newly created node
Handle updates to other auxiliary variables, e.g. size in this case
* Adds an element to the front of the list.
*
* #param e the new element to add
*/
public void addFirst(E e) {
Node<E> first = new Node<>(e);
first.next = this.head;
this.head = first;
this.size++;
}
I am getting this mystical error:
The operator > is undefined for the argument type(s)
java.lang.Comparable, java.lang.Comparable
What the heck?
(here's the code)
public class BST<T extends Comparable<T>> {
public static class Node<P extends Comparable<P>> {
P val;
Node<P> left;
Node<P> right;
public Node() {
}
public Node(P val) {
this.val = val;
}
}
Node<T> root;
private void addValHelper(Node root, Node newNode) {
if (root.val > newNode.val) { // <-- ERROR IS HERE
if (root.left == null) {
root.left = newNode;
} else {
addValHelper(root.left, newNode);
}
} else {
if (root.right == null) {
root.right = newNode;
} else {
addValHelper(root.right, newNode);
}
}
}
}
Java doesn't have operator overloading. You can't compare Comparable types with >. You need to use root.val.compareTo(newNode.val) instead.
As an aside:
Comparable is an interface, not a class
You don't need to specify <P extends Comparable<P>>
It might make more sense to move the addValHelper code into the Node class itself
It might make sense for Node to implement Comparable.
This way, your code feels a lot more idiomatic and you don't expose fields of Node to BST.
public class BST<T implements Comparable<T>> {
private final Node<T> root;
/** Presumably this is run when a value is added.. */
private void addValueHelper(Node rootNode, Node newNode) {
rootNode.attachChild(newNode);
}
public static class Node implements Comparable<T> {
private final T val;
private Node left;
private Node right;
public Node(T val) {
this.val = val;
}
public int compareTo(Node other) {
return this.val.compareTo(other.val);
}
/**
* Takes the given node and compares it with the current node.
* If the current node is greater than the given node, the given node is placed to the left.
* Otherwise it is placed to the right.
*/
protected void attachChild(Node newNode) {
if (this.compareTo(newNode) == 1) {
if (this.left == null) {
this.left = newNode;
return;
}
this.left.attachChild(newNode);
return;
}
if (this.right == null) {
this.right = newNode;
return;
}
this.right.attachChild(newNode);
}
}
}
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.
I'm so close to completing my project, but I am stuck on one part. I am trying to implement abstract methods from a file called AbstractLinkedList.java in my file MyLinkedList.java.
Here are the two project files:
AbstractLinkedList.java
/*
Models a doubly-linked list with dummy header and tail.
You should extend this class with your MyLinkedList to complete
the implementation.
*/
public abstract class AbstractLinkedList<E> {
protected final Node<E> myFront,
myBack; // dummy header/tail
protected int mySize; // # of elements in list
/* Constructs a new empty list. */
public AbstractLinkedList() {
myFront = new Node<E> (null);
myBack = new Node<E> (null);
myBack.setPrevious(myFront);
myFront.setNext(myBack);
mySize = 0;
}
/* Inserts the given element at the given index. */
public void add(int index, E element) {
checkIndex(index, size());
Node<E> curr = getNodeAt(index);
// create the new node to hold the new element
Node<E> newNode = new Node<E> (element, curr.getPrevious(), curr);
(newNode.getNext()).setPrevious(newNode);
(newNode.getPrevious()).setNext(newNode);
mySize++;
}
/* Appends the given element to the end of this list. Returns true. */
public void add(E element) {
add(size(), element);
}
/*
Removes the element of this list at the given index and returns it.
Throws IndexOutOfBoundsException if index is out of range.
*/
public void remove(int index) {
checkIndex(index, size() - 1);
// get the node to remove, and update the references
Node<E> nodeToRemove = getNodeAt(index);
(nodeToRemove.getPrevious()).setNext(nodeToRemove.getNext());
(nodeToRemove.getNext()).setPrevious(nodeToRemove.getPrevious());
mySize--;
}
/*
Sets the element of this list at the given index to have the given value.
Throws IndexOutOfBoundsException if index is out of range.
*/
public void set(int index, E value) {
checkIndex(index, size() - 1);
getNodeAt(index).element = value;
}
/* Returns the number of elements in this list. */
public int size() {
return mySize;
}
/* Returns true if this list contains no elements. */
public boolean isEmpty() {
return mySize == 0;
}
/* Removes all elements from this list. */
public void clear() {
myFront.setNext(myBack);
myBack.setPrevious(myFront);
mySize = 0;
}
/*
Helper method: Throws an IndexOutOfBoundsException
if 0 <= index <= max is not true.
*/
private void checkIndex(int index, int max) throws IndexOutOfBoundsException {
if (index < 0 || index > max) throw new IndexOutOfBoundsException();
}
/*
Removes the given element from this list, if it is present in the list.
Returns true if the element was in the list and was removed.
*/
public abstract boolean remove(E element);
/* Returns true if this list contains the given element. */
public abstract boolean contains(E element);
/*
Returns the element of this list at the given index.
Throws IndexOutOfBoundsException if index is out of range.
*/
public abstract E get(int index);
/*
Returns the first index where the given element occurs in this list,
or -1 if the element is not in this list.
*/
public abstract int indexOf(E element);
/*
Returns the last index where the given element occurs in this list,
or -1 if the element is not in this list.
*/
public abstract int lastIndexOf(E element);
/*
Helper method: returns the node at the given index.
-1 returns dummy header, and size() returns the dummy tail.
Consider the effiency of this method. How can you write it
minimize the number of comparisons?
*/
protected abstract Node < E > getNodeAt(int index) throws IndexOutOfBoundsException;
/*
Returns an array containing all of the elements in this list
in the correct order.
*/
public abstract E[] toArray();
/*
Returns a String representation of this list.
*/
public abstract String toString();
/* Represents one doubly-linked node in the list. */
protected class Node<E> {
private E element;
/* The data element */
private Node < E > next;
/* Reference to the next node in the list */
private Node<E> prev;
/* Reference to the previous node in the list */
/* Constructs a new node to store the given element, with no next node. */
public Node(E element) {
this(element, null, null);
}
/* Constructs a new node to store the given element and the given next node. */
public Node(E element, Node<E> prev, Node<E> next) {
this.element = element;
this.prev = prev;
this.next = next;
}
/* Accessor methods. */
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public Node<E> getPrevious() {
return prev;
}
/* Mutator methods.*/
public void setElement(E el) {
element = el;
}
public void setNext(Node<E> newNext) {
next = newNext;
}
public void setPrevious(Node<E> newPrev) {
prev = newPrev;
}
/* Returns a string representation of this node. */
public String toString() {
return "(" + element + ")";
}
}
}
The file that I have written is MyLinkedList.java (found below).
public class MyLinkedList<Object> extends AbstractLinkedList<Object>{
private Node first, last;
private int mySize;
/** Create a default list */
public MyLinkedList() {
}
/** Inserts the given element at the given index. */
public void add(int index, Object element) {
checkIndex(index, size());
Node curr = getNodeAt(index);
// create the new node to hold the new element
Node newNode = new Node(element, curr.getPrevious(), curr);
(newNode.getNext()).setPrevious(newNode);
(newNode.getPrevious()).setNext(newNode);
mySize++;
}
/** Removes all elements from this list. */
public void clear() {
myFront.setNext(myBack);
myBack.setPrevious(myFront);
mySize = 0;
}
/** Appends the given element to the end of this list. Returns true. */
public void add(Object element) {
add(size(), element);
}
/**
Removes the element of this list at the given index and returns it.
Throws IndexOutOfBoundsException if index is out of range.
*/
public void remove(int index) {
checkIndex(index, size() - 1);
//get the node to remove, and update the references
Node nodeToRemove = getNodeAt(index);
(nodeToRemove.getPrevious()).setNext(nodeToRemove.getNext());
(nodeToRemove.getNext()).setPrevious(nodeToRemove.getPrevious());
mySize--;
}
/*
Sets the element of this list at the given index to have the given value.
Throws IndexOutOfBoundsException if index is out of range.
*/
public void set(int index, Object value) {
checkIndex(index, size() - 1);
getNodeAt(index).element = value;
}
/** Returns the number of elements in this list. */
public int size() {
return mySize;
}
/** Returns true if this list contains no elements. */
public boolean isEmpty() {
return mySize == 0;
}
/**
Helper method: Throws an IndexOutOfBoundsException
if 0 <= index <= max is not true.
*/
private void checkIndex(int index, int max) throws IndexOutOfBoundsException{
if (index < 0 || index > max)
throw new IndexOutOfBoundsException();
}
/** Override toString() to return elements in the list */
public String toString() {
StringBuffer result = new StringBuffer("[");
Node current = first;
for (int i = 0; i < mySize; i++) {
result.append(current.element);
current = current.next;
if (current != null)
result.append(", "); // Separate two elements with a comma
else
result.append("]"); // Insert the closing ] in the string
}
return result.toString();
}
/**
Helper method: returns the node at the given index.
-1 returns dummy header, and size() returns the dummy tail.
Consider the effiency of this method. How can you write it
minimize the number of comparisons?
*/
#Override
protected MyLinkedList<Object>.Node getNodeAt(int index) throws IndexOutOfBoundsException{
if (index == -1){
return first;
}
else if (index == mySize){
return last;
}
}
/** Return true if this list contains the element o */
public boolean contains(Object o) {
// Implementation left as an exercise
return true;
}
/** Return the element from this list at the specified index */
public Object get(int index) {
// Implementation left as an exercise
return null;
}
/** Returns the index of the first matching element in this list.
* Returns -1 if no match. */
public int indexOf(Object o) {
// Implementation left as an exercise
return 0;
}
/** Returns the index of the last matching element in this list
* Returns -1 if no match. */
public int lastIndexOf(Object o) {
// Implementation left as an exercise
return 0;
}
private class Node {
Object element;
Node next;
Node prev;
/** Constructs a new node to store the given element and the given next node. */
public Node(Object element, Node prev, Node next) {
this.element = element;
this.prev = prev;
this.next = next;
}
/** Accessor methods. */
public Object getElement(){
return element;
}
public Node getNext(){
return next;
}
public Node getPrevious(){
return prev;
}
/** Mutator methods.*/
public void setElement(Object obj){
element = obj;
}
public void setNext(Node newNext){
next = newNext;
}
public void setPrevious(Node newPrev){
prev = newPrev;
}
/** Returns a string representation of this node. */
public String toString() {
return "(" + element + ")";
}
}
#Override
public boolean remove(Object element) {
// TODO Auto-generated method stub
return false;
}
#Override
public Object[] toArray() {
return null;
}
}
The error that I keep getting is with the following line
#Override
protected MyLinkedList<Object>.Node getNodeAt(int index) throws IndexOutOfBoundsException{
if (index == -1){
return first;
}
else if (index == mySize){
return last;
}
}
Eclipse keeps telling me that "The return type is incompatible with AbstractLinkedList.getNodeAt(int)" and I am unable to overcome this obstacle.
Any and all help would be greatly appreciated.
You have a nested Node class in both of your classes.
The method in MyLinkedList is declared to return MyLinkedList.Node, but AbstractLinkedList requires the return type of AbstractLinkedList.Node.
Try changing
Node curr = getNodeAt(index);
to
Node<Object> curr = getNodeAt(index);
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...