0

im trying to create my own BinaryTree class and i also got a JUnit-Class which outputs the tests for the non added value and the first added value as a Nullpointer..

The Nullpointer occurs in my BinaryTree class at the while-loop, which doesnt make sense to me, as i've got the following lines of code to check it:

 if(key.compareTo(current.key) == 0) { 
          return current.value;
      }
      return null;
  }

The first added value should be checked first (at least i think)

Here is my code:

public class BinaryTree<K extends Comparable<K>, V>{ 
    int count = 0;
  //Please don't add any further attributes.
  private K key;
  private V value;
  private BinaryTree<K,V> left, right;
  private BinaryTree<K,V> root;
  /**
   * Constructor creates new BinaryTree instance, initially without child nodes.
   */
  // Done!!
  public BinaryTree(K key, V value){
      this.value = value;
      this.key = key;
      left = null;
      right = null;
  }

  /**
   * Stores a key-value pair in the tree.
   * If the key has already been stored, then the current value for this key
   * is replaced by the new value.
   */
  public void put(K key, V value) {
      BinaryTree<K,V> newNode = new BinaryTree<K,V>(key, value);
        if (root == null) {
          root = newNode;
          root.value = value;
          root.key = key;
          count += 1;
          return;
        }
        BinaryTree<K,V> current = root;
        BinaryTree<K,V> parent;
          while (true) {
            parent = current;
            if (key.compareTo(current.key) == -1) {
              current = current.left;
              if (current == null) {
                parent.left = newNode;
                count += 1;
                return;
              }
            } else {
              current = current.right;
              if (current == null) {
                parent.right = newNode;
                count += 1;
                return;
              }
            }


        }
      }


  /**
   * Returns the value object stored with the given key.
   * Returns null if the key is unknown.
   */
  public V get(K key) {
      BinaryTree<K,V> current = root;

      while(key.compareTo(current.key) != 0) {

          if(key.compareTo(current.key) < 0) {
            current = current.left;  
          } else if(key.compareTo(current.key) > 0) {
            current = current.right;           
          } 
      }
      if(key.compareTo(current.key) == 0) { 
          return current.value;
      }
      return null;
  }
}



John Kugelman
  • 349,597
  • 67
  • 533
  • 578

0 Answers0