简体   繁体   中英

Deserilizing n-ary tree

I'm supposed to deserialize a n-ary tree.

this code creates my tree:

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

where the first argument is the parent and the second argument is a initializer list that is the children of the first argument.

my serialize function looks like this: (I'm using 2 functions to do this)

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

After calling foodtree.serialize("foodtree.out"). My .OUT file looks like this:

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 

I wish to write a deserialize function which will take this file in and create a n-ary tree. The in each line, first word in the .OUT file has to be the parent node and the following words have to be the children. I don't know how I should go about this. Any help is appreciated.

All I have so far is: void Ntree::deserialize(string& filename); :P

Think of it this way.

How did you create the tree in the first place?

Do the same, except instead of using literal values get the values from the file. Also use a loop instead of separate addChildren statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM