kpeeters / tree.hh

An STL-like C++ header-only tree library
GNU General Public License v3.0
132 stars 31 forks source link

Question about merge. #9

Open rdebroiz opened 3 years ago

rdebroiz commented 3 years ago

I try to merge two tree together but I'm not sure i properly understood what it says in the doc.

for instance with the siblings of the first level of two trees used as ranges for the merge function, i expect something like:

a               a               a
└── a      +    └── b       =   ├── a
    └── a           └── b       │   └── a
                                └── b
                                    └── b

but the result is

┌── a
│   └── a
│       └── a
└── b
    └── b

code to demonstrate:

#include <trie.h>

using namespace std;

void print_branches(const tree<char>& tree) {
    tree<char>::leaf_iterator it = tree.begin_leaf();
    while(tree.is_valid(it)) {
        string branch;
        tree_node_<char>* node = it.node;
        while(node != tree.head && node != nullptr) {
            branch += ">-";
            branch.push_back(node->data);
            node = node->parent;
        }
        reverse(branch.begin(), branch.end());
        ++it;
        cout << branch << endl;
    }
}

int main(int argc, const char** argv) {
    tree<char> tree1, tree2;
    tree<char>::sibling_iterator it1, it2;
    it1 = tree1.insert(tree1.begin(), 'a');
    it1 = tree1.append_child(it1, 'a');
    it1 = tree1.append_child(it1, 'a');
    it2 = tree2.insert(tree2.begin(), 'a');
    it2 = tree2.append_child(it2, 'b');
    it2 = tree2.append_child(it2, 'b');

    it1 = tree1.begin();
    it2 = tree2.begin();
    tree1.merge(it1, it1.end(), it2, it2.end());
    print_branches(tree1);
}

output:

a->a->a->
b->b->

insead of

a->a->a->
a->b->b->

Am i correctly using the merge function in conjunction with the sibling_iterator?

xuerenjie124 commented 2 years ago

Hi, I also get that result,do you find the correct way to use that function?