简体   繁体   中英

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.

To set something you would need to do ie 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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