Search code examples
javaalgorithmdata-structuresbinary-search-treecomputer-science

Recursive insert binary search tree JAVA


I have this code and I'm finding difficulties to write it in a recursive way (insert method in Binary search tree)

    public void insert(E element){
        BTNode<E> node=root;
        boolean stop=false;
        while(!stop){
            if(element.compareTo(node.getElement())<0){
                if(node.getLeft()==null){
                    node.setLeft(new BTNode<E>(element));
                    stop=true;
                } else{
                    node=node.getLeft();
                }
            }
            else{
                if(node.getRight()==null){
                    node.setRight(new BTNode<E>(element));
                    stop=true;
                } else{
                    node=node.getRight();
                }
            }
                
        }
        
    }

Solution

  • You could write a method that accepts the root and the element to be inserted and returns the modified root.

    public BTNode<E> insert(BTNode<E> root, E element) {
       if ( root == null ) {
          root = new BTNode<E>(element);
       } else if ( element.compareTo(root.getElement()) < 0 ) {
          root.left = insert(root.left, element);
       } else {
          root.right = insert(root.right, element);
       }
       return root;
    }