我应该反序列化一棵n-ary树。
此代码创建我的树:
foodtree.addChildren("Food", { "Plant", "Animal" } );
foodtree.addChildren("Plant", { "Roots", "Leaves", "Fruits" } );
foodtree.addChildren("Animal", { "Fish", "Mammals", "Birds" } );
foodtree.addChildren("Roots", { "Potatoes", "Carrots" } );
foodtree.addChildren("Leaves", { "Lettuce", "Cabbage" } );
foodtree.addChildren("Fruits", { "Apples", "Pears", "Plums", "Oranges" } );
foodtree.addChildren("Fish", { "Salmon", "Tuna" } );
foodtree.addChildren("Mammals", { "Beef", "Lamb" } );
foodtree.addChildren("Birds", { "Chicken", "Duck" } );
foodtree.addChildren("Salmon", { "Wild", "Farm" } );
foodtree.addChildren("Apples", { "GrannySmith", "Gala" } );
其中第一个参数是父参数,第二个参数是初始化列表,它是第一个参数的子元素。
我的序列化函数如下所示:(我使用2个函数来执行此操作)
template<typename T>
void Ntree<T>:: serializeHelper (node* r, ofstream& ofs)
{
if(r->child.size() > 0)
ofs<<r->val <<" ";
for(int i=0; i < r->child.size(); i++)
ofs<<r->child[i]->val <<" ";
if(r->child.size() > 0)
ofs << "\n";
vector<node*> vt = r->child;
for (int j = 0; j < vt.size(); j++)
serializeHelper(vt[j], ofs);
}
template <typename T>
void Ntree<T>::serialize(std::string filename)
{
ofstream ofs(filename);
serializeHelper(root, ofs);
}
在致电foodtree.serialize(&#34; foodtree.out&#34;)之后。我的.OUT文件如下所示:
Food Plant Animal
Plant Roots Leaves Fruits
Roots Potatoes Carrots
Leaves Lettuce Cabbage
Fruits Apples Pears Plums Oranges
Apples GrannySmith Gala
Animal Fish Mammals Birds
Fish Salmon Tuna
Salmon Wild Farm
Mammals Beef Lamb
Birds Chicken Duck
我希望编写一个反序列化函数,它将获取此文件并创建一个n-ary树。在每行中,.OUT文件中的第一个单词必须是父节点,以下单词必须是子节点。我不知道该怎么做。任何帮助表示赞赏。
到目前为止,我只有:void Ntree :: deserialize(string&amp; filename); :P
答案 0 :(得分:0)
这样想。
你是如何创建树的?
执行相同操作,除了使用文字值而不是从文件中获取值。也可以使用循环而不是单独的addChildren语句。