简体   繁体   English

我的二叉搜索树实现中的 insert() 方法有什么问题?

[英]What's wrong with my insert() method in my Binary Search Tree implementation?

I tried to create a recursive method to insert an element into my binary search tree;我试图创建一个递归方法来将一个元素插入到我的二叉搜索树中; however, I can't seem to find the error in my code (I suspect it has something to do with references).但是,我似乎在我的代码中找不到错误(我怀疑它与引用有关)。

public class BST<E extends Comparable<E>> {

    private class BSTNode implements Comparable<BSTNode> {

        public E data;
        public BSTNode left;
        public BSTNode right;

        public BSTNode(E data) {
            this.data = data;
        }

        @Override
        public int compareTo(BSTNode o) {
            return this.data.compareTo(o.data);
        }
    }

    public BSTNode root;

    public void insert(E data) {
        insertRec(root, new BSTNode(data));
    }

    private void insertRec(BSTNode current, BSTNode newNode) {
        if (current == null) {
            current = newNode;
            return;
        }
        if (current.compareTo(newNode) > 0) {
            insertRec(current.right, newNode);
        }
        else if (current.compareTo(newNode) < 0) {
            insertRec(current.left, newNode);
        }
    }

This makes no sense:这没有任何意义:

 if (current == null) {
            current = newNode;
            return;
        }

current.right and current.right can be null , so you never actually add something to a Node. current.rightcurrent.right可以是null ,所以你永远不会真正向节点添加东西。

To set something you would need to do ie current.right = newNode要设置您需要做的事情,即current.right = newNode

This should work:这应该有效:

public class BST<E extends Comparable<E>> {

    private class BSTNode implements Comparable<BSTNode> {

        public E data;
        public BSTNode left;
        public BSTNode right;

        public BSTNode(E data) {
            this.data = data;
        }

        @Override
        public int compareTo(BSTNode o) {
            return this.data.compareTo(o.data);
        }
    }

    public BSTNode root;

    public void insert(E data) {
        root = insertRec(root, new BSTNode(data));
    }

    private BSTNode insertRec(BSTNode current, BSTNode newNode) {
        if (current == null){
            return newNode;
        }

        if (current.compareTo(newNode) > 0) {
           current.right = insertRec(current.right, newNode);
        } else {
            current.left = insertRec(current.left, newNode);
        }

        return current;
    }
}

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

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