I have browsed the other questions and found solutions as to how to do a deep copy of objects that contain references. I am specifically wanting to make a deep copy of a tree. Logically, each tree node contain references to its children nodes. Here is the basics of my node class
public class BSTNode implements Comparable, Serializable { private String token; private int count; private BSTNode leftChild; private BSTNode rightChild;
I know I must only be making a shallow copy because when I make a copy of tree1, called tree2, and edit tree1 the edits also appear on tree2. Here is my copy method within my BSTNode class
When I wish to copy the entire tree, I call that above copy method from my BSTree class using the methods below. (I have 2 methods because this is a homework assignment that requires a copy method that calls a preorder traversal method)public BSTNode copy() { BSTNode obj = null; try{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(this); out.flush(); out.close(); ObjectInputStream in= new ObjectInputStream(new ByteArrayInputStream( bos.toByteArray())); obj = (BSTNode) in.readObject(); } catch(Exception e) { e.printStackTrace(); } return obj; }
I use these lines to create the new tree and assign the copy to itpublic BSTNode copy() { BSTNode copiedTreeRoot = new BSTNode(); return copyTree(copiedTreeRoot,root); } public BSTNode copyTree(BSTNode copiedTreeRoot, BSTNode otherTreeRoot) { if(otherTreeRoot == null) { copiedTreeRoot = null; } else { copiedTreeRoot = otherTreeRoot.copy(); copyTree(copiedTreeRoot.getLeft(), otherTreeRoot.getLeft()); copyTree(copiedTreeRoot.getRight(), otherTreeRoot.getRight()); } return copiedTreeRoot; }
BSTree tree2 = new BSTree(); tree2.setRoot(tree1.copy());
And further along when I make changes to tree1, tree 2 also changes. I have no clue what I'm doing wrong. I believe it must be somewhere in how I return the new tree or something. Any help is greatly appreciated!!
--- Update ---
I tried this edit to my copy method, but it made no difference.
public BSTNode copy() { BSTNode obj = null; try{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(this); out.flush(); out.close(); ObjectInputStream in= new ObjectInputStream(new ByteArrayInputStream( bos.toByteArray())); obj = (BSTNode) in.readObject(); } catch(Exception e) { e.printStackTrace(); } if(leftChild != null) { obj.setLeft(leftChild.copy()); } if(rightChild != null) { obj.setRight(rightChild.copy()); } return obj; }