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

时间:2019-11-22 10:29:07

标签: c++ tree

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

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 ++或任何其他语言来提取这种树形迭代循环?

1 个答案:

答案 0 :(得分:1)

根据我的正确理解,您希望拥有该算法的通用版本。

我不知道您想使哪些零件通用,因此这是一个非常简单的解决方案,其中的所有零件都是通用的。

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;
}

我希望那是你想要的!

相关问题