Ümit Ümit - 7 months ago 13
Java Question

How to Clone BinaryNode

I am trying to mirror a binary tree as it is shown in the picture

two binary trees

public void mirror(BinaryNode<AnyType> node){
if (node == null) {
return;
}
printPreOrder();

node.setRight(node.getLeft()); // problem is here
this.replace(node.getRight());
System.out.println();
printPreOrder();

}
private void replace(BinaryNode<AnyType> node){
if (node == null ) {
return;
}

BinaryNode<AnyType> temp = node.getLeft();
node.setLeft(node.getRight());
node.setRight(temp);

replace(node.getRight());
replace(node.getLeft());


}


When I set the left of tree to the right side, and when I change something on it, the code also changes the left side of tree, which is undesirable.
outputs: first preOrderPrint: 50 9 10 6 8 7 20 - second preOrderPrint: 50 9 10 8 6 9 10 8 6
How can I fix this problem?

Answer

You need to copy the node and then set the copy of it. Otherwise you'll end up with the same references. I don't know how BinaryNode is implemented, maybe there's a method called copy or duplicate or something like that?

Comments