I have a function that prints tree nodes from left to right.
void PrintTree()
{
...
Print(curentNode);
...
}
But now I want to add a function that prints nodes that meet some condition. For example, print only such nodes, strings of which start with a given string. So it would look like
void PrintTreeByCondition(string a)
{
...
if(IsPrefix(a,curentNode->stringVar))
Print(curentNode);
...
}
But then I have two functions with the same code, with the difference in one line. How would I avoid code duplication here?
UPD: Traverse code:
void BinTree::TraverseTree()
{
std::stack<TreeNode*> s;
s.push(root);
TreeNode* curentNode = s.top();
while (curentNode != nullptr|| s.empty() == false)
{
while (curentNode != nullptr)
{
s.push(curentNode);
curentNode = curentNode->GetLeft();
}
curentNode = s.top();
s.pop();
// do stuff
curentNode = curentNode->GetRight();
}
}