Solution to 7041: Cloning tree nodes
See code at solutions/code/tutorialquestions/question7041
A tree node can be cloned using a recursive method as follows:
public TreeNode<E> clone() {
TreeNode<E> result = new TreeNode<E>(getNumberOfChildren());
result.setKey(getKey());
for(int i = 0; i < getNumberOfChildren(); i++) {
result.setChild(i, getChild(i).clone());
}
return result;
}
Notice that TreeNode<E> result = new TreeNode<E>(getNumberOfChildren());
causes a brand new TreeNode
object to be allocated (creating a genuine copy), while result.setKey(getKey());
sets the key
of result
to refer to the same object as the key
of the object on which clone()
is invoked. Thus the key itself is not cloned.