c++ - 如果我们知道父子之间的联系,如何递归地将元素插入 n 数组树结构?

标签 c++ c++11 tree parent-child tree-structure

设A为root,其子节点为B、C、D 我们也知道 B 有一个 child E。 我的问题是,如果我们知道元素之间的联系,如何递归插入元素而不是逐个添加元素?

class Node { 
public: 
string key; 
vector<Node*> child; 

// constructor 
Node(string data) 
{ 
    key = data; 
} 
}; 
//main
Node* root = new Node("A"); 
(root->child).push_back(new Node("B")); 
(root->child).push_back(new Node("C")); 
(root->child).push_back(new Node("D"));  
(root->child[0]->child).push_back(new Node("E"));

最佳答案

您可以在树上递归移动并在找到父节点时添加您的元素。

考虑这个函数:

bool insert(string s, string t, Node * root) { // will return true is success
    if (root->key == s) { // found the parent -> insert the new node
        (root->child).push_back(new Node(t)); 
        return true;
    }
    bool ans = false; 
    for( int i =0; i< (root->child).size();i++){
        ans |= insert(s, t, root->child[i]); recursive call to all the children
    }
    return ans; 
}

现在主要使用它时:

int main()
{
    Node* root = new Node("A"); 
    cout << "status adding B to A: " << insert("A", "B", root) << endl; // return true
    cout << "status adding E to G: " << insert("G", "E", root) << endl; // return false
    cout << "status adding E to B: " << insert("B", "E", root) << endl; // return true
    return 0;
}

希望对您有所帮助!

关于c++ - 如果我们知道父子之间的联系,如何递归地将元素插入 n 数组树结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53503123/

相关文章:

c++ - std::nth_element 导致段错误;我错过了什么,还是 STL 中的错误?

c++ - glPopAttrib & GL_INVALID_OPERATION

javascript - 遍历对象获取键和所有父键

c++ - 通过指针数组实现树的优点?

c++ - 如何在 vim 中创建映射以自动执行 .h C++ 文件的 ifdef 命令

c++ - glsl - 获取像素颜色 [像素着色器]

c++ - 在运行时处理类型删除的数据 - 如何不重新发明轮子?

c++ - 在类内声明模板化函数(通过容器类型)并在模板类之外通过容器类型定义它 -

c++ - 为什么我的 glBindBufferRange 偏移对齐不正确?

java - 在java中将树结构转换为二维 'grid'数组