如何在C++中提取树迭代

how to extract a tree iteration in C++

本文关键字:提取 迭代 C++      更新时间:2023-10-16

我已经重复了好几次类似的代码。伪代码是这样的:

stack.push(root)
while stack size > 0
  node = stack.pop()
  if condition_1
    if node is leaf
      if condition_2
        // do something,
        // for example, push node into a vector and return the vector
    else
      stack.push(children of node)

或者像这样:

stack.push(root)
while stack size > 0
  node = stack.pop()
  if condition_1
    if node is leaf
      if condition_2 // or no condition_2 and return true directly
        return true
    else
      stack.push(children of node)
return false

这两个代码段之间的区别在于,第一个代码段迭代所有叶节点,而第二个代码段具有中断逻辑。通常我做的主要工作是condition_2及其范围。其他台词只是在重复自己。

那么有没有办法用C++或任何其他语言提取这种树迭代循环呢?

正如我正确理解的那样,您希望拥有此算法的通用版本。

我不知道你想使哪些部分成为通用的,所以这是一个非常简单的解决方案,其中一切都是通用的。

template <class NodeType, class TraversalPredicate, class LeafPredicate,
          class TerminalPredicate, class ChildrenGetter>
bool findIf(NodeType *root, TraversalPredicate shouldTraverse,
            LeafPredicate isLeaf, TerminalPredicate shouldFinish,
            ChildrenGetter getChildren) {
  std::stack<NodeType *> stack;
  stack.push(root);
  while (not stack.empty()) {
    auto *node = stack.top();
    stack.pop();
    if (not shouldTraverse(node))
      continue;
    if (isLeaf(node)) {
      if (shouldFinish(node)) {
        return true;
      }
    } else {
      for (auto *child : getChildren(node)) {
        stack.push(child);
      }
    }
  }
  return false;
}

我希望这就是你要找的!