我正在爲二叉樹製作一個遞歸插入方法。此方法無法將節點添加到樹中。我似乎無法找到這種方法有什麼問題。構造函數爲子節點和父節點提供一個字符串標籤。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);
}
}
}
什麼問題呢?它只是沒有生成適當的BST或者你得到任何異常?你的第一條款的條件似乎是錯誤的。請檢查。您已檢查父母是否較少 – SacJn