重建一棵树

Rebuilding a tree

本文关键字:一棵树 重建      更新时间:2023-10-16

我有一棵树,形式如下:

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向量中。

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中的所有节点吗?

你有这样的想法吗?

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