【问题标题】:Rebuilding a tree重建一棵树
【发布时间】:2017-11-22 06:56:34
【问题描述】:

我有一棵树,格式如下:

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中吗?

【问题讨论】:

  • 我不确定我是否理解。你有什么?你打算从哪里获取节点?

标签: c++ algorithm tree


【解决方案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) ;
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2014-11-01
    相关资源
    最近更新 更多