2017-11-22 3 views
0

Iは以下のフォームのツリーを有する再構築:ツリー

Node[0]: 
     type: "element", 
     name: "div", 
     data: "", 
     attributes:{"class":"wrapper"}, 
     children: 
       Node[0]: 
         type: "text", 
         name: "", 
         data: "Hello", 
         attributes: {}, 
         children: null, 
       Node[1]: 
         type: "element", 
         name: "span", 
         data: "", 
         attributes: {"class:leftMenu", "class:Applyshadow"}, 
         children: 
           Node[0]: 
             type: "text", 
             name: "", 
             data: "World!", 
             attributes: {}, 
             children: null 
Node[1]: 
     type: "element", 
     name: "div", 
     data: "", 
     attributes: {"class":"secondDiv", "id":"submit"}, 
     children: null 

タイプのノード「要素」は子供を持つことができ、それがなければ子供ノードのベクトルとして格納されています。

struct Attribute{ 
    std::string name; 
    std::string value; 
}; 

struct Node{ 
    std::string type; 
    std::string name; 
    std::string data; 
    std::vector<Attribute> attributes; 
    std::vector<Node> children; 
}; 


class HtmlTree{ 
    public: 
     std::vector<Node> nodes; 
     void buildTree(GumboNode*) 
} 

ツリー構造が来るgumboNodeからgumboParserの一部であり、buildTreeメソッドの実装では、私は、ツリー内のすべてのノードを印刷することができていますが、私は以下のクラスでツリーを再構築しようとしていますそれをnodesベクターに保存する方法について説明してください。

Void HtmlTree::buildTree(GumboNode* root){ 
    print root->type 
    vector children = root->children; 
    for each child in children: 
     if child->type == "element": 
      print child->type; 
      buildTree(child) 
     elif child->type == "text": 
      print child->type; 
} 

上記の擬似コードは、ベクトルnodes内のすべてのノードを格納するために同じ再帰的なアプローチを利用する方法で私を助けてtree..can誰か内のすべてのノードの種類を出力しますか?

+0

わかりません。あなたは何を持っていますか?どこからノードを取るつもりですか? –

答えて

1

あなたはこのようなことに気付いていますか?

void HtmlTree::buildTree(GumboNode *root) { 
    nodes = buildTreeImp(root) ; 
} 

Node HtmlTree::buildTreeImp(GumboNode* root){ 
    Node result ; 
    vector children = root->children; 
    for each child in children: 
     if child->type == "element": { 
      nodes.push_back(buildTree(child)) 
     elif child->type == "text": { 
      Node text_node ; 
      text_node.type = child.type ; 
      // set other attributes 
      nodes.push_back(text_node) ; 
    } 
}