首页 > 解决方案 > 在我的通用 BinaryTree 中找不到第一个/非附加值

问题描述

我试图创建我自己的 BinaryTree 类,我还得到了一个 JUnit-Class,它输出非附加值的测试和第一个附加值作为 Nullpointer..

Nullpointer 出现在我的 BinaryTree 类中的 while 循环中,这对我来说没有意义,因为我有以下代码行来检查它:

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

应该首先检查第一个附加值(至少我认为)

这是我的代码:

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;
  }
}



标签: javabinary-tree

解决方案


推荐阅读