Java binary search tree - implementation implementation

I have this problem with implementing binary search tree insertion. Now I tried this with both the recursive method and the iterative one. The way I got so far is “at best”, since for a tree of size = 31609 and tree height = 35 the insert takes about 100 seconds and it is expected that WAAAAAAY will be lower by about one second. Can someone please give me a hint what can i do wrong?

Here is the code of what I managed to do so far (Insert without duplicates):

void insert(int val){
    if(this.elem < val){
        if(this.right != null){
            this.right.insert(val);
        }
        else{
            nodes++;
            this.right = new Node(val);
        }
    }
    else if(this.elem > val){
        if(this.left != null){
            this.left.insert(val);
        }
        else{
            nodes++;
            this.left = new Node(val);

        }
    }
    else {
        return;
    }
}
+4
source share
1 answer

, 270 , .

:

public void insert(int val) {

        if (root == null) {
            nodes++;
            root = new Node(val);
        } else if (!root.exists(val)) {
            root.insert(val);
        }

    }

exists(), :

boolean exists(int val) {
            return val == this.elem
                    || (val < this.elem ? (this.left != null && this.left.exists(val))
                            : (this.right != null && this.right.exists(val)));
        }

, , , , , , , ! , 100 . , O (n ^ 2 * logn) , 100 - !

, exists().

+1

All Articles