0

I am trying to type a deep copy method in a BinarySearchTree class, but I'm having difficulty in understanding the logic here. Could you please explain to me how I could go through with this?

This is my main():

public static void main(String[] args) {
        BinarySearchTree<String> bst1 = new BinarySearchTree<String>();
        BinarySearchTree<String> bst2 = new BinarySearchTree<String>();

        String[] words = {"hello", "world", "how", "are", "you", "doing"};

        for (int i = 0; i < words.length; i++) {
            bst1.add(words[i]);
        }

        bst1.copy(bst2);

}

And these are my copy() methods (keep in mind that these are in the BinarySearchTree class):

public void copy(BinarySearchTree<E> bst2){
    copy(this.root, bst2.root);
}

private void copy(Node<E> bst1, Node<E> bst2){      
    bst2.data = bst1.data;

    if(bst1.left != null){
        bst2.left = bst1.left;
        copy(bst1.left, bst2.left);
    }
    if(bst1.right != null){
        bst2.right = bst1.right;
        copy(bst1.right, bst2.right);
    }
}

Please help me understand the logic and make the code work correctly.

Thanks!

Monil
  • 169
  • 1
  • 1
  • 11

1 Answers1

0

I realized my mistake. I was supposed to use bst2 as a BinarySearchTree instead of a Node. This would be the method after making it correct.

public void copy(BinarySearchTree<E> bst2){
    copy(bst1.root, this);
}

private void copy(Node<E> bst1, BinarySearchTree<E> bst2) {
    if (bst1 == null) {
        return;
    } else if (bst1.left == null && bst1.right == null) {
        bst2.add(bst1.data);
    } else {
        bst2.add(bst1.data);

        if (bst1.left != null) {
            copy(bst1.left, bst2);
        }

        if (bst1.right != null) {
            copy(bst1.right, bst2);
        }
    }
}
Monil
  • 169
  • 1
  • 1
  • 11