繁体   English   中英

二叉搜索树添加算法的实现

[英]Implementation of binary search tree add algorithm

我必须在Java中为BST实现add方法,但无法使我的add函数正常工作。 有人可以帮我吗?

private boolean add(E x, BinaryNode<E> currentNode){

        if (currentNode == null){
            currentNode = new BinaryNode<>(x);
            size++;
            return true;
        }

        if (currentNode.element.compareTo(x) == 0){
            return false;
        }

        else if((currentNode.element.compareTo(x) < 0)){

            if(currentNode.left == null){
                currentNode.left = new BinaryNode<>(x);
                size++;
                return true;

            } else {
                add(x, currentNode.left);
            }

        }

        else if(currentNode.element.compareTo(x) > 0){

            if(currentNode.right == null){
                currentNode.right = new BinaryNode<>(x);
                size++;
                return true;

            } else {
                add(x, currentNode.right);
            }

        }

        return false;
    }

    public boolean add(E x){
        return this.add(x, root);
    }

我看到的一个问题是,当您分配根元素时,会将其分配给局部变量。 这显然行不通。

private boolean add(E x, BinaryNode<E> currentNode){
  /////// REMOVE
        if (currentNode == null){
            currentNode = new BinaryNode<>(x);
            size++;
            return true;
        }
  ///////

并添加此

public boolean add(E x){
    if( root == null ) {
      root = new BinaryNode<>(x);
      size++;
      return true;
    }  else
      return this.add(x, root);
}

基本上,子树的根可能会更改,这是一个递归,要使其正常工作,返回值应该是子树的新根,无论它是否更改。

以下是从Java中的BST impl中获取的add()方法,并通过了所有测试用例:

/**
 * Add a new value.
 *
 * @param v
 */
@Override
public void add(T v) {
    root = add(root, v);
}

/**
 * Add to a subtree start from given node.
 *
 * @param current root of a subtree to add node to,
 * @param v
 * @return the new root of subtree,
 */
protected BSTNode<T> add(BSTNode<T> current, T v) {
    if (current == null) { // subtree is empty,
        size++;
        return new BSTNode<>(v);
    }

    // compare,
    int compareFlag = v.compareTo(current.value);

    // check this or subtree,
    if (compareFlag < 0) { // smaller, go to left subtree,
        current.left = add(current.left, v);
    } else if (compareFlag > 0) { // larger, go to right subtree,
        current.right = add(current.right, v);
    } else { // equals, ignore it,
    }

    return current;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM