C++ design question on traversing binary trees
- by user231536
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:
I settled on using the functor based approach because I see that boost graph does this (vertex visitors). Also I tend to repeat the same code to traverse the tree and do different things
at each node. Is this a good design to get rid of duplicated code? What other alternative designs are there?
How do I use this to create a new binary tree from an existing one? I can keep a stack on the
visit functor if I want, but it gets tied to the algorithm in visitor.
How would I incorporate postorder traversals here ? Another functor class?