我有一张以下形式的树:
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
“element”类型的节点可以有子节点,如果是,则将子节点存储为节点向量。我正在尝试使用以下类重建树:
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
向量中。 / p>
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;
}
上面的Pseudocode打印树中所有节点的类型。有人可以帮助我利用相同的递归方法来存储向量nodes
中的所有节点吗?
答案 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) ;
}
}