This question is how do I create a new node correctly to implement the insert method? I am using eclipse IDE to write this code, but I am stuck.
public KeyValueDSBinarySearchTree(Class<K> keyType,
Class<V> valueType,
DSComparator<K> keyComparator) {
ObjectTools.paramNullCheck(keyType, "keyType");
ObjectTools.paramNullCheck(valueType, "valueType");
ObjectTools.paramNullCheck(keyComparator, "keyComparator");
rootNode = null;
count = 0;
levelCount = 0;
lastReplacedPair = null;
lastDeletedPair = null;
}
#Override
public DSKeyValuePair<K, V> insert(K key, V value) {
DSKeyValuePair<K, V> node;
if (rootNode == null) {
count++;
return node;
}
if (key.compareTo(node.getKey())<0) {
rootNode.left = insert(key, value);
}
else {
rootNode.right = insert(key, value);
}
return node;
}
Related
package linkedList.list;
import linkedList.node.ListNode;
public interface LinkedList<N extends ListNode<T>,T>
{
public boolean isEmpty();
public int size();
public String toString();
public T[] toArray(Class<? extends T> cl);
public LinkedList<N,T> fromArray(T[] array) throws ListAccessError;
}
package linkedList.list;
import linkedList.node.ListNode;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public abstract class BasicList<N extends ListNode<T>,T> implements LinkedList<N,T> {
N root;
int size;
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public N getRoot() {
return root;
}
public void setRoot(N newRoot) {
root = newRoot;
}
public T[] toArray(Class<? extends T> cl) {
T[] array = (T[]) Array.newInstance(cl,size());
ListNode<T> node = getRoot();
for (int index = 0; index < size(); index++) {
array[index] = node.getValue();
node = node.getNext();
}
return array;
}
public String toString() {
if (isEmpty()) {
return "[]";
} else {
ListNode<T> currentNode = getRoot();
StringBuilder string = new StringBuilder("[" + currentNode.getValue());
while ((currentNode = currentNode.getNext()) != null) {
string.append("," + currentNode.getValue());
}
string.append("]");
return string.toString();
}
}
public String toString(int n) {
if (isEmpty()) {
return "[]";
} else {
ListNode<T> currentNode = getRoot();
StringBuilder string = new StringBuilder("[" + currentNode.getValue());
int added = 0;
while (added < n && (currentNode = currentNode.getNext()) != null) {
string.append("," + currentNode.getValue());
added++;
}
if (currentNode != null) {
string.append(",...");
}
string.append("]");
return string.toString();
}
}
}
package linkedList.list;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;
import jdk.nashorn.internal.ir.IfNode;
import linkedList.node.ListNode;
import linkedList.node.SingleLinkNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class SingleLinkList<T> extends BasicList<SingleLinkNode<T>,T> implements List<T> {
public SingleLinkList<T> fromArray(T[] array) throws ListAccessError {
for (int index = array.length-1; index >= 0; index--) {
add(0,array[index]);
}
return this;
}
ListNode<T> getNode(int index) throws ListAccessError {
// Is the list empty? If so, cannot access the node.
if (isEmpty()) {
throw new ListAccessError("Cannot get node. List is empty.");
}
// Is the given index negative? If so, this is an error.
if (index < 0) {
throw new ListAccessError("Cannot get node. Negative index.");
}
ListNode<T> currentNode = getRoot(); // start at the root
while (index != 0 && currentNode != null) { // walk along the list (if haven't reached the end by hitting null node)
currentNode = currentNode.getNext(); // by gettting next node in the list
index--; // and reducing index by one
}
// Reached the end of the list (by hitting null node)? If so, cannot access the required node.
if (currentNode == null) {
throw new ListAccessError("Cannot get node. Not enough nodes in the list.");
}
// Successfully found node by walking through until index was zero.
return currentNode;
}
public T get(int index) throws ListAccessError {
return getNode(index).getValue();
}
#Override
public void add(int index, T value) throws ListAccessError {
if (index > size() || index < 0) {
throw new ListAccessError("Index bigger than size.");
}
SingleLinkNode<T> newNode = new SingleLinkNode<T>(value);
SingleLinkNode<T> current = getRoot();
if(index==0) {
setRoot(newNode);
newNode.setNext(current);
size++;
} else {
while(--index > 0) {
current = current.getNext();
}
newNode.setNext(current.getNext());
current.setNext(newNode);
size++;
}
}
#Override
public T remove(int index) throws ListAccessError {
if (index >= size() || index < 0) {
throw new ListAccessError("Index out of bounds");
}
if (isEmpty()) {
throw new ListAccessError("List is empty cannot remove from list");
}
SingleLinkNode<T> current = getRoot();
SingleLinkNode<T> nextItem = getRoot().getNext();
return null;
}
}
package linkedList.node;
public class SingleLinkNode<T> implements ListNode<T>
{
private T value;
private SingleLinkNode<T> next;
public SingleLinkNode(T value) {
this.value = value;
next = null;
}
public SingleLinkNode(T value, SingleLinkNode<T> next) {
this.value = value;
this.next = next;
}
public T getValue() {
return value;
}
#Override
public void setValue(T value) {
this.value = value;
}
public SingleLinkNode<T> getNext() {
return next;
}
#Override
public void setNext(ListNode<T> node) {
next = (SingleLinkNode<T>) node;
}
public String toString() {
return value + (getNext() != null ? "=>" + getNext() : "");
}
}
I have just implemented the add method which takes the index and the value and inserts it into that position in the List. However when researching how to remove at the index I am unable to find anything that removes the node with just the given index. Any help is welcome and thanks in advance for any solutions!
When removing a node from a linked list at I position all you need to do is
Get to the node at i-1, let's name it 'n1'
Get the node n2=n1.next.next
Make n1.next =n2
You simply remove the "link" to the requested node at i and it's no longer part of the linked list.
Firstly, you have to check if this it is 0-th index you have to remove, so you have to shift root. Then for removing node at i-th root, all you have to do this:
nodeBeforeI.setNext(nodeBeforeI.getNext().getNext());
The complete code:
public T remove(int index) throws ListAccessError {
if (index >= size() || index < 0) {
throw new ListAccessError("Index out of bounds");
}
if (isEmpty()) {
throw new ListAccessError("List is empty cannot remove from list");
}
SingleLinkNode<T> current = getRoot();
SingleLinkNode<T> removed;
if (index == 0){
removed = current;
setRoot(current.getNext()); // setting root to root.next
}else{
for (int i = 0; i < index -1; i++){
current = current.getNext();
}
removed = current.getNext();
current.setNext(current.getNext().getNext());
}
return removed.getValue();
}
I've been struggling with implementing a Binary Search Tree with the Iterator method. I've been checking out this algorithm out on WikiPedia:
def search_recursively(key, node):
if node is None or node.key == key:
return node
if key < node.key:
return search_recursively(key, node.left)
# key > node.key
return search_recursively(key, node.right)
I translated it to Java:
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private int count = 0;
#Override
public boolean hasNext()
{
return count++ < size;
}
#Override
public T next()
{
return search(root, root.word);
}
public T search(BST root, T word)
{
if (root == null || root.word.compareTo(word) == 0)
{
return root.word;
}
if (root.word.compareTo(word) < 0)
{
return search(root.left, word);
}
return search(root.right, word);
}
};
When trying to run the program I only get the root element of the BST:
MyWordSet bst = new MyWordSet();
T bst = new T("one");
T bst = new T("two");
T bst = new T("three");
T bst = new T("four");
T bst = new T("five");
T bst = new T("six");
bst.add(w1);
bst.add(w2);
bst.add(w3);
bst.add(w4);
bst.add(w5);
bst.add(w6);
Iterator<T> it = bst.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
So the output is:
one
one
one
one
one
one
So why does this method inside my Iterator not work for me to get to the whole tree? I really can't figure out what is wrong here and why it only prints out one when it should go down the tree.
You simply do not update the current_node.
The equivalent of current_node = node is missing.
Well, after having changed the code, here revised answer:
import java.util.Iterator;
import java.util.Stack;
/**
*
* #author jk
*/
public class BSTIterator<T> implements Iterator<T> {
public static final class BST<T> {
private BST<T> left;
private BST<T> right;
private T word;
private BST(T word) {
this.word = word;
}
}
private final Stack<BST<T>> stackBST = new Stack<>();
public BSTIterator(final BST<T> root) {
// push all most left entries of the tree to the stack
BST<T> currBST = root;
while (currBST != null) {
stackBST.push(currBST);
currBST = currBST.left;
}
}
#Override
public boolean hasNext() {
return !stackBST.isEmpty();
}
#Override
public T next() {
BST<T> currBST = stackBST.pop();
// check if we are on the most right entry
final boolean notMostRightEntry = currBST.right != null;
if (notMostRightEntry) {
// take next right entry
BST<T> nextBST = currBST.right;
while (nextBST != null) {
// push this next right entry on the stack
stackBST.push(nextBST);
nextBST = nextBST.left;
}
}
return currBST.word;
}
public static void main(String[] args) {
BST<Integer> root = new BST<>(20);
root.left = new BST<>(5);
root.right = new BST<>(30);
root.left.right = new BST<>(10);
root.right.left = new BST<>(25);
root.right.right = new BST<>(40);
root.right.left = new BST<>(35);
root.right.left.left = new BST<>(32);
for (Iterator<Integer> bstIt = new BSTIterator<>(root); bstIt.hasNext();) {
System.out.println("val: " + bstIt.next());
}
}
}
So I have to modify the BST class to include a PrintRange function, which would essentially print all nodes between two values in order.
Here is the class
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
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; // Number of nodes in the BST
/** Constructor */
BST() { root = null; nodecount = 0; }
/** Reinitialize tree */
public void clear() { root = null; nodecount = 0; }
/** Insert a record into the tree.
#param k Key value of the record.
#param e The record to insert. */
public void insert(Key k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
// Return root
public BSTNode getRoot()
{
return root;
}
/** Remove a record from the tree.
#param k Key value of record to remove.
#return The record removed, null if there is none. */
public E remove(Key k) {
E temp = findhelp(root, k); // First find it
if (temp != null) {
root = removehelp(root, k); // Now remove it
nodecount--;
}
return temp;
}
/** Remove and return the root node from the dictionary.
#return The record removed, null if tree is empty. */
public E removeAny() {
if (root == null) return null;
E temp = root.element();
root = removehelp(root, root.key());
nodecount--;
return temp;
}
/** #return Record with key value k, null if none exist.
#param k The key value to find. */
public E find(Key k) { return findhelp(root, k); }
/** #return The number of records in the dictionary. */
public int size() { return nodecount; }
private E findhelp(BSTNode<Key,E> rt, Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0) return rt.element();
else return findhelp(rt.right(), k);
}
/** #return The current subtree, modified to contain
the new item */
private BSTNode<Key,E> inserthelp(BSTNode<Key,E> rt,
Key k, E e) {
if (rt == null) return new BSTNode<Key,E>(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
/** Remove a node with key value k
#return The tree with the node removed */
private BSTNode<Key,E> removehelp(BSTNode<Key,E> rt,Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it
if (rt.left() == null) return rt.right();
else if (rt.right() == null) return rt.left();
else { // Two children
BSTNode<Key,E> temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right()));
}
}
return rt;
}
private BSTNode<Key,E> getmin(BSTNode<Key,E> rt) {
if (rt.left() == null) return rt;
return getmin(rt.left());
}
private BSTNode<Key,E> deletemin(BSTNode<Key,E> rt) {
if (rt.left() == null) return rt.right();
rt.setLeft(deletemin(rt.left()));
return rt;
}
private void printhelp(BSTNode<Key,E> rt) {
if (rt == null) return;
printhelp(rt.left());
printVisit(rt.element());
printhelp(rt.right());
}
private StringBuffer out;
public String toString() {
out = new StringBuffer(400);
printhelp(root);
return out.toString();
}
private void printVisit(E it) {
out.append(it + "\n");
}
public void printPreOrder(BSTNode<E, E> root) {
if (root != null) {
System.out.println(root.element());
printPreOrder(root.left());
printPreOrder(root.right());
}
}
public void printInOrder(BSTNode<E, E> root) {
if (root != null) {
printInOrder(root.left());
System.out.println(root.element());
printInOrder(root.right());
}
}
public void printPostOrder(BSTNode<E, E> root) {
if (root != null) {
printPostOrder(root.left());
printPostOrder(root.right());
System.out.println(root.element());
}
}
}
Here's what I have so far for the PrintRange function:
public void printRange(BSTNode<E, E> root, E low, E high) {
if (root != null) {
printRange(root.left(), low, high);
if (root.element().toString().compareTo(low.toString()) > 0 && root.element().toString().compareTo(high.toString()) < 0)
System.out.println(root.element());
printRange(root.right(), low, high);
}
}
But it's giving me an error. Any suggestions on how to compare elements/nodes/I'm not even certain in a BST?
Here's the driver if it helps
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Lab8a {
public static void main(String[] args) {
BST<String, String> tree = new BST<String, String>();
Scanner fileScan = null, scan = new Scanner(System.in);
//Open file
try {
fileScan = new Scanner(new File("inventory.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Reads elements from file
while (fileScan.hasNextLine()) {
String s = fileScan.nextLine();
tree.insert(s, s);
}
System.out.println("\nRange");
tree.printRange(tree.getRoot(), "A", "B");
}
}
And the text file:
CT16C1288B
DT14B1225F
MI15B1250A
MI15B1251A
HO03N1095A
HY07D1095BQ
KI04D2593C
DG12A1240AQ
HY03G2593BQ
TO30A1310A
HO03N1095AQ
HO01H1351C
HO01H1350C
FT18A1288B
LR15A1000A
BM12E1000A
VW02B3113A
NI23H1230AQ
LX03D2503A
LX03D2502A
LX03D2502A
VW22A3113B
VW22B3113A
I was mistaken. There was no error. I must have fixed the code at some point.
I'm having an issue with implementing this BinarySearchTree listed below. For some context, I'm creating a binary search tree based off of an interface that requires generics and a comparable key.I think that there is a logic error in the code that is stumping me and it's in the insert method in the BinarySearchTree, but I'm not 100% sure.
Below is the class for my Node, which is used in my BST.
public class MyNodeClass<Key extends Comparable<Key>, Value>{
private Key key;
private Value value;
private MyNodeClass<Key,Value> left = null;
private MyNodeClass<Key,Value> right = null;
public MyNodeClass(Key key, Value val)
{
this.key = key;
this.value = val;
}
public void setKey(Key key){
this.key = key;
}
public void setValue(Value value){
this.value = value;
}
public Key getKey(){
return this.key;
}
public Value getValue(){
return this.value;
}
public void setLeft(MyNodeClass<Key, Value> l){
this.left = l;
}
public void setRight(MyNodeClass<Key, Value> r){
this.right = r;
}
public MyNodeClass<Key,Value> getLeft(){return this.left;}
public MyNodeClass<Key,Value> getRight(){return this.right;}
public int compareTo(Key that){
return(this.getKey().compareTo(that));
}
}
public class MyBinarySearchTree<Key extends Comparable<Key>, Value> implements BinarySearchTree<Key,Value> {
private MyNodeClass<Key, Value> root;
public MyBinarySearchTree(){
root = null;
}
#Override
public boolean isEmpty() {
return root == null;
}
#Override
public Value insert(Key key, Value val) {
MyNodeClass<Key,Value> newNode = new MyNodeClass<Key,Value>(key,val);
newNode.setKey(key);
newNode.setValue(val);
if(root==null){
root = newNode;
return(newNode.getValue());
}
else{
MyNodeClass<Key,Value> current = newNode;
MyNodeClass<Key,Value> parent;
while(true){
{
parent = current;
if(current.compareTo(key) == 1)
{
current = current.getLeft();
if(current == null)
{
parent.setLeft(newNode);
return parent.getLeft().getValue();
}
}
else if(current.compareTo(key) == -1){
current = current.getRight();
if(current == null)
{
parent.setRight(newNode);
return parent.getRight().getValue();
}
}
else{
if(current.compareTo(key) == 0){
current.setKey(key);
current.setValue(val);
return current.getValue();
}
}
}
}
}
}
#Override
public Value find(Key key) {
MyNodeClass<Key, Value> current = root;
while (current.compareTo(key) != 0)
{
if (current.compareTo(key) == 1)
{
current = current.getLeft();
} else {
current = current.getRight();
}
if(current == null)
return null;
}
return current.getValue();
}
#Override
public Value delete(Key key) {
MyNodeClass<Key,Value> current = root;
MyNodeClass<Key,Value> parent = root;
boolean isLeftChild = true;
while(current.compareTo(key) != 0) {
parent = current;
if (current.compareTo(key) == 1) {
isLeftChild = true;
current = current.getLeft();
} else {
isLeftChild = false;
current = current.getRight();
}
if(current == null)
return null;
}
if(current.getLeft() == null && current.getRight() == null) {
if (current == root) {
root = null;
} else if (isLeftChild) {
parent.setLeft(null);
} else{
parent.setRight(null);
}
return current.getValue();
}
else if(current.getRight() == null)
{
if(current == root) {
root = current.getLeft();
}
else if(isLeftChild) {
parent.setLeft(current.getLeft());
}
else{
parent.setRight(current.getLeft());
}
return current.getValue();
}
else if(current.getLeft() == null)
{
if(current == root)
root = current.getRight();
else if(isLeftChild)
parent.setLeft(current.getRight());
else
parent.setRight(current.getRight());
return current.getValue();
}
else
{
MyNodeClass<Key,Value> successor = getSuccessor(current);
if(current == root)
root = successor;
else if(isLeftChild)
parent.setLeft(successor);
else
parent.setRight(successor);
successor.setLeft(current.getLeft());
return current.getValue();
}
}
#Override
public String stringLevelOrder() {
return(LevelOrder(root));
}
private MyNodeClass<Key,Value> getSuccessor(MyNodeClass<Key,Value> deleteNode)
{
MyNodeClass<Key,Value> successorParent = deleteNode;
MyNodeClass<Key,Value> successor = deleteNode;
MyNodeClass<Key,Value> current = deleteNode.getRight();
while(current != null)
{
successorParent = successor;
successor = current;
current = current.getLeft();
}
if(successor != deleteNode.getRight())
{
successorParent.setLeft(successor.getRight());
successor.setRight(deleteNode.getRight());
}
return successor;
}
public static void main(String[] args)
{
MyBinarySearchTree<Double, MyStudent> BST = new MyBinarySearchTree<Double, MyStudent>();
MyStudent myStud1 = new MyStudent();
MyStudent myStud2 = new MyStudent();
MyStudent myStud3 = new MyStudent();
MyStudent myStud4 = new MyStudent();
MyStudent myStud5 = new MyStudent();
myStud1.init("Clarise", 1.1);
myStud2.init("Christopher", 1.2);
myStud3.init("John", 1.3);
myStud4.init("Chloe", 1.4);
myStud5.init("Goo", 1.5);
System.out.println(BST.insert(myStud1.getGPA(), myStud1));
System.out.println(BST.insert(myStud2.getGPA(), myStud2));
System.out.println(BST.insert(myStud3.getGPA(), myStud3));
System.out.println(BST.insert(myStud4.getGPA(), myStud4));
System.out.println(BST.insert(myStud5.getGPA(), myStud5));
System.out.println("Delete Key 1.0: " +BST.delete(1.3));
System.out.println("Delete Key 1.4: " +BST.delete(1.4));
System.out.println("Is Empty?: " +BST.isEmpty());
System.out.print("Find 3.9: "+ BST.find(3.9));
}
}
The result of the main is the following:
{Clarise:1.1}
{Christopher:1.2}
{John:1.3}
{Chloe:1.4}
{Goo:1.5}
Delete Key 1.0: null
Delete Key 1.4 null
Is Empty?: false
Find 3.9: null
I'm not entirely sure what the issue is and I've had some help from others, however they can't find the problem. Hoping that someone else can see something that we don't see.
In your insert method, after you've checked that root is not null, you are inserting newNode into the newNode instead of inserting it into the root.
This:
MyNodeClass<Key,Value> current = newNode;
MyNodeClass<Key,Value> parent;
Should be:
MyNodeClass<Key,Value> current = root;
MyNodeClass<Key,Value> parent;
P.S. any kind of testing would show you the problem with your insert within a minute. You could write a size() method and see that your inserts are not working, you could write a toString() method and see the state of the tree, finally you could debug.
MyNodeClass<Key,Value> current = newNode;
There is problem here.
If a tree is not empty, then your "current" should begin at root node. What you done is insert "newNode" to "newNode".
Change the code to be:
MyNodeClass<Key,Value> current = root;
i had to implement a binary tree pictured on this file
together with the class Diagramm and binary tree for orientation.
So following the text and the Pictures i have to implement a constructor, a get- and insert method for this binary tree.
public class BinaryTree {
private Node root = null;
private static class Node {
private Integer key;
private String value;
private Node left = null;
private Node right = null;
public Node(Integer key, String value) {
this.key = key;
this.value = value;
}
}
public boolean insert(Integer key, String value) {
if (root == null) {
root = new Node(key, value);
return true;
} else {
return insert(root, key, value);
}
}
private boolean insert(Node node, Integer key, String value) {
if (key.equals(node.key)) {
// duplicate
return false;
} else if (key < node.key) {
if (node.left == null) {
node.left = new Node(key, value);
return true;
} else {
return insert(node.left, key, value);
}
} else if (key > node.key) {
if (node.right == null) {
node.right = new Node(key, value);
return true;
} else {
return insert(node.right, key, value);
}
}
return false;
}
// not tested, crass assumptions, public domain
public String get(Integer key) {
return get(root, key); // start search from the root.
}
public String get(Node node, Integer key) {
String result = null; // Assume key is not found
if (node.key.equals(key)) { // Key matches? This is the result.
return node.value;
} else {
if (key < node.key && node.left != null) { // key is lower than
// current node,
// and there is a left
// branch, keep
// search from there.
result = get(node.left, key);
} else if (key > node.key && node.right != null) { // key is greater
// than current
// node,
// and there is
// a left
// branch,
// keep search
// from there.
// The key >
// node.key is
// arguably
// redundant.
result = get(node.right, key);
}
}
return result;
}
How can i implement a correct main function for testing? And on top i have to visualize the binary tree with help of graphviz and adding a method in the node class which creates a string for the dot-code. How does it work with Eclipses?
The get method will start at a specific node within the tree, and check whether that node itself meets the criteria. If it does, it returns the value. If not, it will defer to the appropriate branch and continue searching.
// not tested, crass assumptions, public domain
public String get(Integer key) {
return get(root, key); // start search from the root.
}
public String get(Node node, Integer key) {
String result = null; // Assume key is not found
if (node.key.equals(key)) { // Key matches? This is the result.
return node.value;
} else {
if (key < node.key && node.left != null) { // key is lower than current node,
// and there is a left branch, keep
// search from there.
result = get(node.left, key);
} else if (key > node.key && node.right != null) { // key is greater than current node,
// and there is a left branch,
// keep search from there.
// The key > node.key is arguably
// redundant.
result = get(node.right, key);
}
}
return result;
}
If you choose procedural approach, right way to do things will be that:
public class BinaryTree {
private Node root = null;
private static class Node {
private Integer key;
private String value;
private Node left = null;
private Node right = null;
public Node(Integer key, String value) {
this.key = key;
this.value = value;
}
}
public boolean insert(Integer key, String value) {
if (root == null) {
root = new Node(key, value);
return true;
} else {
return insert(root, key, value);
}
}
private boolean insert(Node node, Integer key, String value) {
if (key.equals(node.key)) {
// duplicate
return false;
} else if (key < node.key) {
if (node.left == null) {
node.left = new Node(key, value);
return true;
} else {
return insert(node.left, key, value);
}
} else if (key > node.key) {
if (node.right == null) {
node.right = new Node(key, value);
return true;
} else {
return insert(node.right, key, value);
}
}
return false;
}
}
Now compare it to OOP approach and choose, which one you like more:
public class BinaryTree {
private Node root = null;
private static class Node {
private Integer key;
private String value;
private Node left = null;
private Node right = null;
public Node(Integer key, String value) {
this.key = key;
this.value = value;
}
private boolean insert(Integer key, String value) {
if (key.equals(this.key)) {
// duplicate
return false;
} else if (key < this.key) {
if (left == null) {
left = new Node(key, value);
return true;
} else {
return left.insert(key, value);
}
} else if (key > this.key) {
if (right == null) {
right = new Node(key, value);
return true;
} else {
return right.insert(key, value);
}
}
return false;
}
}
public boolean insert(Integer key, String value) {
if (root == null) {
root = new Node(key, value);
return true;
} else {
return root.insert(key, value);
}
}
}
Solution is simple. For insert operation:
If there is no root in the tree yet, create one.
Otherwise add a new value to the root node.
Inserting a value to some node (starting from root one):
If node's key equals to the inserted key => we have a duplicate and won't proceed any further.
If inserted key is lesser than node's key, do:
If there is no left subtree, create a new node and assign it as a left child.
If there is already a left subtree, recursively add new (key, value) to it.
If inserted key is greater than node's key, do: (by analogy with #2)