2015-10-22 38 views
0

我正在爲二叉樹製作一個遞歸插入方法。此方法無法將節點添加到樹中。我似乎無法找到這種方法有什麼問題。構造函數爲子節點和父節點提供一個字符串標籤。Java二叉樹插入方法不起作用

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或者你得到任何異常?你的第一條款的條件似乎是錯誤的。請檢查。您已檢查父母是否較少 – SacJn

回答

0

編輯:這個答案指的是問題的原始版本。

當您撥打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); 
    } 
} 
}