【问题标题】:Java Binary Tree insert method not workingJava二叉树插入方法不起作用
【发布时间】:2016-01-21 06:15:48
【问题描述】:

我正在为二叉树创建递归插入方法。此方法无法将节点添加到树中。我似乎找不到这种方法有什么问题。构造函数为子节点和父节点获取一个字符串标签。

 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 还是您遇到任何异常?您的第一个 if 子句的条件似乎是错误的。检查一下。您已检查父级是否较小

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


【解决方案1】:

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

当您调用inserts(this.childrenLeft, aNode); 时,您仍然在同一个节点;即this 仍然指的是旧的父级。

相反,您应该执行以下操作:

childrenLeft.insert(childrenLeft, aNode);

其实insert的第一个参数是多余的,应该重构去掉。

【讨论】:

    【解决方案2】:

    我想你可能需要这样的东西。

    对代码进行了注释,以便您了解发生了什么...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-16
      • 2016-05-09
      • 1970-01-01
      • 2012-08-21
      • 2020-08-22
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      相关资源
      最近更新 更多