简体   繁体   English

为 BST 实现 Add 方法

[英]Implementing Add Method for BST

I am trying to implement an insertion method in a BST but have encountered some problems.我正在尝试在 BST 中实现插入方法,但遇到了一些问题。 Given the surrounding code:给定周围的代码:

public class BinarySearchTree<E> {
  private BinaryNode<E> root;  
  private int size;          
  private Comparator<E> comparator;

    /**
     * Constructs an empty binary search tree, sorted according to the specified comparator.
     */
    public BinarySearchTree(Comparator<E> comparator) {
        root = null;
        size = 0;
        this.comparator = comparator;
    }

    private static class BinaryNode<E> {
        private E element;
        private BinaryNode<E> left;
        private BinaryNode<E> right;

        private BinaryNode(E element) {
            this.element = element;
            left = right = null;
        }   
    }

     //Other methods
}

what is wrong with my implementation:我的实现有什么问题:


    /**
     * Inserts the specified element in the tree if no duplicate exists.
     * @param x element to be inserted
     * @return true if the the element was inserted
     */
    public boolean add(E x) {
        return add(root, x);
    }

    private boolean add(BinaryNode<E> n, E x) {
        if(n == null) {
            n = new BinaryNode<E> (x);
            size++;
            return true;
        }
        int compResult = comparator.compare(x, n.element);
        
        if(compResult<0){
            return add(n.left, x);
        } else if(compResult>0) {
            return add(n.right, x);
        }else {
            return false;
        }
    }

When testing inserting only one element I get null as the return value of the root but I can't really see what's going wrong.在测试仅插入一个元素时,我得到 null 作为根的返回值,但我真的看不出出了什么问题。 Thanks for the help!谢谢您的帮助!

When you assign当你分配

    n = new BinaryNode<E> (x)

in add() you are assigning to a local variable.add()中,您分配给局部变量。 That doesn't add the new node to the tree;这不会将新节点添加到树中; there are no references from the existing tree to the new node that way.这种方式没有从现有树到新节点的引用。

There are numerous ways to fix it, but this is likely the reason why you never see root change away from null ;有很多方法可以修复它,但这可能是您永远不会看到root更改远离null的原因; you never assign to it anywhere.你永远不会在任何地方分配给它。

Pointers would be nice here, they make it easier to pass a variable by reference, but in Java I think you would need to pass along the location where you need to put the new node some other way.指针在这里会很好,它们可以更容易地通过引用传递变量,但是在 Java 中,我认为您需要传递需要以其他方式放置新节点的位置。 I haven't used the language in 20 years, so I am not too sure, though.我已经有 20 年没有使用过这种语言了,所以我不太确定。

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

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