Java二进制树插入方法无法正常工作

时间:2015-10-22 03:45:11

标签: java recursion binary-tree binary-search-tree nodes

我正在为二叉树制作递归插入方法。此方法无法将节点添加到树中。我似乎无法找到这种方法的错误。构造函数为子节点和父节点采用字符串标签。

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

    }

}

2 个答案:

答案 0 :(得分:0)

编辑:此答案指的是问题的原始版本。

当你致电inserts(this.childrenLeft, aNode);时,你仍然在同一个节点;即this仍指旧父母。

相反,你应该做类似的事情:

childrenLeft.insert(childrenLeft, aNode);

实际上,insert的第一个参数是多余的,您应该重构以删除它。

答案 1 :(得分: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);
  }
 }
}