c++ - C++ - 在 n 叉树上迭代
问题描述
这是在 n 元树上具有迭代算法的函数,给定 a name
,并使用它来查找父树,parent tree's data
如果找到则返回,"ZERO"
如果没有找到父树,并且"NA"
如果name
不在Tree<string>*
向量中的任何树中。它大部分时间都有效,但偶尔会给出错误的输出,"ZERO"
应该找到父级,主要在leaves
.
string getSource(const string name) const { // no recursion
if (existInVector(name, trees)) { // vector of Tree<string>*
queue<Tree<string>> treesQueue;
vector<Tree<string>*>::const_iterator it = trees.begin();
for (; it != trees.end(); ++it) { // for each tree
treesQueue.push(**it); // push tree
for (int i = 0; i < (**it).root->numChildren; ++i) // push children
treesQueue.push((**it).root->children[i]);
while (!treesQueue.empty()) {
Tree<string> temp = treesQueue.front(); // pop front
treesQueue.pop();
for (int i = 0; i < temp.root->childCount; ++i) { // check
if (temp.root->children[i].root->data == name)
return temp.root->data;
}
}
if (it == trees.end()-1 && treesQueue.empty())
return "ZERO";
}
}
return "NA";
}
这是树的类模板:
template <class T>
class Tree {
private:
Node<T>* root;
public:
// ... member functions ...
};
template <class T>
class Node {
private:
T data;
int numChildren;
Tree<T>* children; // Tree<T> array
};
有时得到错误结果的可能原因是什么?
// example with wrong result
Tree<string> tree; // below is what is inside, root is Node "G", "H" is child of "G" and so on
G
\-H
\-I
\-J
tree.getSource("J") == "ZERO"; // Supposed to be "I"
解决方案
您应该推送您访问的当前节点/树的子节点。
我还删除了一些副本。
std::string getSource(const std::string& name) const {
if (!existInVector(name, trees)) { // vector of Tree<string>*
return "NA";
}
std::queue<const Tree<std::string>*> treesQueue;
for (const auto& tree : trees) {
treesQueue.push(&tree);
while (!treesQueue.empty()) {
const auto& current = *treesQueue.front();
treesQueue.pop();
for (int i = 0; i != current.root->childCount; ++i) {
const auto& child = current.root->children[i];
if (child.root->data == name)
return current.root->data;
treesQueue.push(&child);
}
}
}
return "ZERO";
}
推荐阅读
- react-native - React Native View 不显示任何内容
- php - 如何使用 Symfony 4 中的事件处理异常?
- javascript - this.map.set(key,value) 函数在 angualr 6 typescript 2.9.2 中不起作用
- html - Booststrap 表插入模数后断裂
- django - Django:无法创建通用外键对象
- jquery - 如何在悬停时为 input[type="submit"] 的“值”设置动画?
- javascript - 在 Traccar 应用程序中更改或添加元素
- c - 错误“表达式必须具有恒定值”
- php - Guzzle:魔术请求方法需要一个 URI 和可选的选项数组
- c# - Is it possible to get index of selected items in DataGridViewCheckBoxColumn?