I have such a task at university to write a visitor, which computes the AbstractTree depth. Here is the tree:
public abstract class AbstractTree {
public abstract void Accept(AbstractVisitor abstractVisitor);
}
public class Leaf : AbstractTree {
public override void Accept(AbstractVisitor visitor) {
visitor.VisitLeaf(this);
}
}
public class Node : AbstractTree {
private AbstractTree Left { get; set; }
private AbstractTree Right { get; set; }
public Node(AbstractTree left, AbstractTree right) {
Left = left;
Right = right;
}
public override void Accept(AbstractVisitor visitor) {
visitor.VisitNode(this);
if (Left != null)
Left.Accept(visitor);
if (Right != null)
Right.Accept(visitor);
}
}
And AbstractVisitor:
public abstract class AbstractVisitor {
public abstract void VisitLeaf(Leaf tree);
public abstract void VisitNode(Node tree);
}
But how do I write the concrete DepthVisitor? I know how to perform this task, when the visitor knows about the tree structure (depth-computing visitor that knows about the tree structure), but in this case, the Visitor has almost no knowledge about the tree structure (it has to, the task is formulated like this).
You could explot some properties of a tree and store the depth of each visited node in the visitor.
Your visitor could keep a map of (tree, depth) pairs.