简体   繁体   English

如果我们知道父子关系,如何递归地将元素插入n数组树结构?

[英]How to insert elements to n array tree structure recursively if we know connection between parent and children?

It is given that A is root and its children are B, C, D and also we know that B has a child E. My question is how to insert elements recursively instead of adding element by element if we know connection between them? 假设A是根,其子是B,C,D,我们也知道B有一个子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"));

You can move recursively over the tree and add you element when find the parent node. 您可以在树上递归移动,并在找到父节点时添加元素。

Consider this function: 考虑以下功能:

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

Now when using it in the main: 现在在主要使用它时:

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

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM