如何从树中检索每个元素

How to retrieve every single element from a tree?

本文关键字:元素 检索      更新时间:2023-10-16

我被困在这里好几天了。有没有人可以看看toString方法在行类,我怎么能从点的树检索每一个点,并从点的字符值?我知道在vector或array中,我们可能会使用for循环并执行类似find(points[I])的操作,但我在这里真的没有线索。

   **std::string toString() const
   {
      string s;
      for(int i = 0; i != points.size(); i++)
      {
         //Maybe use points.find(???) here to retrieve the point
         s.push_back(point.getType()); //Just for demonstration, this does not work
         return s;
      }
   }**
};

所以我不能修改binNode binTree类。而且我不能在Point类中使用print方法,因为print()方法会在新行中打印每个元素。但是我们必须从每个点检索char值,并将所有点的char值附加到一个String中。非常感谢你给我的提示!

binNode模板并不真正支持这种用法,因为它不公开它的子元素。它也不提供iterator。这使得在类之外的代码中遍历树变得不可能。子类甚至对子类都不可见,所以你不能那样扩展它。

您可以为Point专门化binNode模板,并强制它向全局string发出输出:

std::string output; // a global
template <>
class binNode<Point> {
    void print() const {
        if (left != NULL) left->print();
        output += nodeData.getType();
        if (right != NULL) right->print();
    }
};
// in some function
output.clear(); // remember to clear previous output
points.print(); // the string now has the output from `print`

如果你有多个线程调用print,即使在单独的bintree上,这当然不会起作用。

要正确实现这些功能,您唯一的选择是修改bintreebinNode