Search code examples
c++treetraversalinsertion

Problem with tree traversal method for n-ary tree


I have a Tree class with a private nested Node class. I am trying to write a traversal method and the problem is that I am only able to print out the first level of my tree. I am not sure if there is something wrong with mu traversal method. Because I don't see another way to write it. I think the problem comes from ins method which inserts a child in a specific index of a tree. I think I am inserting into different objects.

Thank you in advanced for your help


Solution

  • Your insertion is broken. You first insert nodes B and C by copying them:

    _info->getChildren()[index] = childTree;
    

    and only then you insert nodes D and E into original trees n1_1 and n1_2. The easiest way to somehow fix the error is to change the order of insertions:

    n1_1.ins(0, n1_1_1);
    n1_2.ins(0, n1_2_1);
    n1.ins(0, n1_1);
    n1.ins(1, n1_2);
    

    Alternatively, you could insert nodes directly into the tree. That is, first get corresponding Tree, then insert into it. Keeping your syntax and assuming that some data members are public:

    n1.ins(0, n1_1);
    n1.ins(1, n1_2);
    
    n1._info->_children[0].ins(0, n1_1_1);  // n1._info->_children[0]) is not n1_1
    n1._info->_children[1].ins(1, n1_2_1);  // n1._info->_children[1]) is not n1_2
    

    Your code has a lot of other issues to address. If you could rewrite it with std::unique_ptrs instead of raw pointers, you'll resolve many of them.