C ++-遍历n元树

时间:2020-05-19 07:47:41

标签: c++ loops tree

这是在给定name的情况下对n元树进行迭代算法的函数,并使用它来查找父树,如果发现则返回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"

有时会得到错误结果的可能原因是什么?

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);

1 个答案:

答案 0 :(得分:1)

您应该推送您访问的当前节点/树的子代。

我还删除了一些副本。

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