我有一个从左到右打印树节点的函数。
void PrintTree()
{
...
Print(curentNode);
...
}
Run Code Online (Sandbox Code Playgroud)
但是现在我想添加一个函数来打印满足某些条件的节点。例如,只打印这样的节点,其中的字符串以给定的字符串开头。所以它看起来像
void PrintTreeByCondition(string a)
{
...
if(IsPrefix(a,curentNode->stringVar))
Print(curentNode);
...
}
Run Code Online (Sandbox Code Playgroud)
但是后来我有两个具有相同代码的函数,不同之处在于一行。我将如何避免代码重复?
UPD:遍历代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)