Skip to content

Latest commit

 

History

History
executable file
·
38 lines (31 loc) · 1.24 KB

c822.md

File metadata and controls

executable file
·
38 lines (31 loc) · 1.24 KB

Back to questions

c822: Problems cloning tree nodes

What happens if you now invoke n1.clone(), where n1 is an object referenced by the following code fragment and TreeNode is the class you produced in question 7041?

TreeNode<String> n1 = new TreeNode<String>(1);
n1.setKey("A");
TreeNode<String> n2 = new TreeNode<String>(1);
n2.setKey("B");
n1.setChild(0, n2);
n2.setChild(0, n1);

Answer the same question for n3.clone(), where n3 is an object referenced by the following code fragment:

TreeNode<String> n3 = new TreeNode<String>(2);
n3.setKey("C");
TreeNode<String> n4 = new TreeNode<String>(1);
n4.setKey("D");
TreeNode<String> n5 = new TreeNode<String>(0);
n5.setKey("E");
n3.setChild(0, n4);
n3.setChild(1, n5);
n4.setChild(0, n5);

If your implementation of clone() runs into problems on these examples then think of a precondition on the arguments of setChild() that will ensure that subsequent calls to clone() work correctly. For this exercise, it is enough just to state this precondition in natural language. If you are ambitious, you might like to try implementing a check for the precondition, i.e., an assertion that tests whether the precondition holds on entry to setChild().