c++c++11treeparent-childtree-structure

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?

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

Solution

  • 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!