2015-10-22 3 views
0

Я делаю рекурсивный метод вставки для двоичного дерева. Этот метод не может добавлять узлы в дерево. я не могу найти, что неправильно с этим методом. конструктор берет строчную метку для дочернего элемента и родительского узла.Java Binary Tree insert метод не работает

public void insert(String aLabel) { 

    //if compare is positive add to right else add to left 
    //basis case: 
    BSTreeNode aNode = new BSTreeNode(aLabel,null); 
    if (aNode.parent == null) { 
     aNode.parent = this; 
    } 
    inserts(this,aNode); 
} 
private void inserts(BSTreeNode aParent, BSTreeNode aNode){ 
    //initially the root node is the parent however a proper parent is found thorough recursion 
    //left recursion: 
    if(aParent.getLabel().compareTo(aNode.getLabel()) <= 0) { 
     if (this.childrenLeft == null) { 
      this.childrenLeft = aNode; 
      aNode.parent = this; 
      return; 
     } else { 
      childrenLeft.inserts(childrenLeft, aNode); 
     } 
    } 
    //right recursion 
    else { 
     if (this.childrenRight==null) { 
      this.childrenRight = aNode; 
      return; 
     } 
     else{ 
      childrenRight.inserts(childrenRight,aNode); 
     } 

    } 

} 
+0

Что проблема? Разве это просто не создает правильный BST или вы получаете какое-либо исключение? Ваше условие предложения first if кажется неправильным. Просто проверьте. Вы проверили, меньше ли родителей – SacJn

ответ

0

EDIT: Этот ответ относится к первоначальному варианту вопроса.

Когда вы звоните inserts(this.childrenLeft, aNode);, вы все еще находитесь на том же узле; то есть this по-прежнему относится к старым родителям.

Вместо этого вы должны сделать что-то вроде:

childrenLeft.insert(childrenLeft, aNode); 

В самом деле, первый параметр insert является излишним, вы должны реорганизовать, чтобы удалить его.

0

Думаю, вам может понадобиться нечто подобное.

код прокомментирован так что вы понимаете, что происходит ...

// insert method takes The Node as a param and a value to store in BT 
public void insert(Node node, int value) { 

//Check that the value param is less than the Node (root) value, 
// If so insert the data to the left of the root node. Else insert   
// the right node as it is a larger number than root 
if (value < node.value) { 
    if (node.left != null) { 
    insert(node.left, value); 
    } else { 
    System.out.println(" Inserted " + value + " to left of " 
     + node.value); 
    node.left = new Node(value); 
    } 
} else if (value > node.value) { 
    if (node.right != null) { 
    insert(node.right, value); 
    } else { 
    System.out.println(" Inserted " + value + " to right of " 
     + node.value); 
    node.right = new Node(value); 
    } 
} 
}