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!