[英]search data in tree structure
您能否推薦一種有效(快速)的在樹狀結構中搜索數據的算法,如下所示:
struct Node
{
std::string value;
Node* parent;
std::vector<Node*> childs;
}
目標是找到Node.value與搜索模式匹配的所有Node。 謝謝
一個簡單的預遍歷:
void match(Node * node, const std::string & value, std::vector<Node*> & result)
{
if (node->value == value)
{
result.push_back(node);
}
for (Node * child : node->childs)
{
match(child, value, result);
}
}
int main()
{
Node * root = /* ... */
std::string value = /* ... */;
std::vector<Node*> matches;
match(root, value, matches);
}
概括為
template<typename Action>
void preorder(Node * node, Action action)
{
action(node);
for (Node * child : node->childs)
{
preorder(child, action);
}
}
int main()
{
Node * root = /* ... */
std::string value = /* ... */;
std::vector<Node*> matches;
preorder(root, [&](Node * node){ if (node->value == value) { matches->push_back(node); } });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.