Code1 has a class implementing TreeVisitor and, when used, calculates and set th
ID: 3824143 • Letter: C
Question
Code1 has a class implementing TreeVisitor and, when used, calculates and set the depth of each Entry in a tree. (To set the AVLEntry instance's depth use the setDepth() method). Remember that a node's depth is one greater than the depth of its parent!
You will also need Code2 which has a class implementing TreeVisitor and, when used, calculates and returns the height of an Entry in a tree. (To set the AVLEntry instance's height use the setHeight() method). Remember that leaves always have a height of 0 and interior nodes have a height one greater than their taller child.
Code2:
Explanation / Answer
For Code 1, we can calculate the depth as:
public class DepthCalculatorVisitor implements TreeVisitor {
/**
* Sets the depth of the leaf node to the value that had been calculated.
*/
@Override
public int visitLeaf(AVLEntry leaf, int depth) {
return 0;
}
@Override
public int visitInterior(AVLEntry node, int depth) {
if (node == null)
return depth;
else
{
//find depth of left Node
int left_depth = visitInterior(node.left,depth);
//find depth of right Node
int right_depth = visitInterior(node.right,depth);
if (left_depth > right_depth)
return (left_depth + 1);
else
return (right_depth + 1);
}
return 0;
}
}