Second opinion needed on Binary Search Tree Insert and Print

Check the comments for the changes that need to be done.

void printPreOrder(Node node){ //rename method to printPreOrder
    if(node == null){
        return;
    }   

    System.out.println(""+node.value); //print here. If you print here it is preorder.
    printInOrder(node.left);
    //don't print here. If you print here it is inorder.
    printInOrder(node.right);
}

Also, in insertStart method, you should return after adding the node.

    if(val < root.value && root.left == null){
        root.left = new Node(val);
        System.out.println("Val inserted to left of root: "+root.left.value);
        return; //add return here
    }

    if(val > root.value && root.right == null){
        root.right = new Node(val);
        System.out.println("Val inserted to right of root: "+root.right.value);
        return; //add return here
    }

If you don’t add the above mentioned return statements, you’ll get output as

3 1 0 1 4 4 5

instead of

3 1 0 4 5

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top