Reputation: 2711
I have a binary tree T which I would like to copy to another tree.
Suppose I have a visit method that gets evaluated at every node:
struct visit
{
virtual void operator() (node* n)=0;
};
and I have a visitor algorithm
void visitor(node* t, visit& v)
{
//do a preorder traversal using stack or recursion
if (!t) return;
v(t);
visitor(t->left, v);
visitor(t->right, v);
}
I have 2 questions:
Upvotes: 0
Views: 1084
Reputation: 24360
3: Create an additional method for each type of traversal you want to do and rearrange the visitor calls:
void preorder_visitor(node* t, visit& v)
{
if (!t) return;
v(t);
visitor(t->left, v);
visitor(t->right, v);
}
void postorder_visitor(node* t, visit& v)
{
if (!t) return;
visitor(t->left, v);
visitor(t->right, v);
v(t);
}
Upvotes: 1
Reputation: 70909
A visitor is a technique. It looks like you've confused the technique with a particular solution. Using a visitor means that some navigation services are provided by the data structure which will communicate with an external object (the visitor) by call-back.
Upvotes: 0