【问题标题】:Recursive Insert for Binary Tree二叉树的递归插入
【发布时间】:2014-12-03 21:33:48
【问题描述】:

我正在编写用于插入二叉搜索树的代码。它适用于我插入的第一个节点,使其成为根,但之后它似乎没有插入任何节点。我确定这是设置左/右参考的问题,但我无法弄清楚。请帮忙!

    //params: key of node to be inserted, parent node
    public void insert(int newKey, TreeNode parent){

    //if the root of the tree is empty, insert at root
    if(this.getRoot() == null){
        this.root = new TreeNode(newKey, null, null);
    }

    //if the node is null, insert at this node
    else if(parent == null)
        parent = new TreeNode(newKey, null, null);


    else{
        //if the value is less than the value of the current node, call insert on the node's left child
        if(newKey < parent.getKey()) {
                insert(newKey, parent.getLeft());
        }
        //greater than value of current node, call insert on node's right child
        else if(newKey > parent.getKey()){
                insert(newKey, parent.getRight());
        }
        //same as value of current node, increment iteration field by one
        else if(newKey == parent.getKey())
            parent.incrementIterations();
    }

}

我的树节点有键、左、右和迭代字段,以及 getter/setter 函数。 先感谢您!

【问题讨论】:

  • 我可以看到的一个问题是 parent 是按值传递的。对父级的更改将是本地副本。您可能需要通过引用传递。
  • 好的,谢谢!我注意到了这一点,并添加了额外的 if 循环来解决它。我相信这可以解决问题: if(newKey

标签: java recursion reference tree binary-tree


【解决方案1】:
public Node insertNode(Node head, int data) {

        if(head == null){
            head = new Node();
            head.data = data;
            return head;
        }
        if(head.data < data) {
            head.right = insertNode(head.right,data);
        } else {
            head.left = insertNode(head.left, data);
        }
        return head;
    }

【讨论】:

    【解决方案2】:

    如果 (parent==null) 您正在创建一个节点,但您没有将它与树关联。它刚刚创建并收集了垃圾。

    你应该使用 insert (newkey, parent) 然后你仍然有树的句柄

    【讨论】:

      【解决方案3】:
      private AVLNode insert(AVLNode root, int value){
          if (root == null) return new AVLNode(value);
      
          if(root.value > value)
              root.leftChild = insert(root.rightChild, value);
          else
              root.rightChild = insert(root.leftChild, value);
      
          return root;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-11-16
        • 2020-07-24
        • 2015-09-19
        • 1970-01-01
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        相关资源
        最近更新 更多