【问题标题】:Implementing Add Method for BST为 BST 实现 Add 方法
【发布时间】:2021-12-29 20:12:38
【问题描述】:

我正在尝试在 BST 中实现插入方法,但遇到了一些问题。给定周围的代码:

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
}

我的实现有什么问题:


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

在测试仅插入一个元素时,我得到 null 作为根的返回值,但我真的看不出出了什么问题。感谢您的帮助!

【问题讨论】:

  • 你想告诉我们什么是 null 还是我们应该只是猜测?
  • 请以某种方式标记返回 null 的行。
  • 只插入一个元素时,根的返回值为null。
  • 我通过 JUnit 测试它。 assertTrue(bstNbrs.add(2), "Should return true when adding non duplicate"); 其中 bstNbrs 只是具有整数值的 bst。然后我做:assertEquals(2, bstNbrs.root.element, "Not correct order");。我有点作弊,因为我删除了属性的私有以便能够访问属性,但我这样做是为了能够测试。

标签: java algorithm recursion data-structures binary-search-tree


【解决方案1】:

当你分配时

    n = new BinaryNode<E> (x)

add() 中,您正在分配一个局部变量。这不会将新节点添加到树中;这种方式没有从现有树到新节点的引用。

有很多方法可以修复它,但这可能是您从未看到root 更改为远离null 的原因;你永远不会在任何地方分配给它。

指针在这里会很好,它们可以更轻松地通过引用传递变量,但在 Java 中,我认为您需要传递需要以其他方式放置新节点的位置。我已经 20 年没用过这种语言了,所以我不太确定。

【讨论】:

    猜你喜欢
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2021-07-14
    • 2013-06-19
    • 1970-01-01
    • 2021-04-04
    • 2016-01-09
    相关资源
    最近更新 更多