I'm trying to merge two trees. This is the recursive function:

void Merge(node *primary,node *secondary)
{
  if(secondary != NULL && primary != NULL)
    {
      Merge(primary->left,secondary->left);
      Merge(primary->right,secondary->right);
    }
  else if(secondary != NULL && primary == NULL)
    {
      primary = new node;
      primary->action = secondary->action;
      primary->left = NULL;
      primary->right = NULL;
      primary->leaf = secondary->leaf;

      Merge(primary->left,secondary->left);
      Merge(primary->right,secondary->right);
    }
  else
    return;
}

Basically, I'm traversing the two trees identically and I create a node in 'primary' if it's NULL and if 'secondary' is not null.

The problem I'm having is that, when I run this, and when I return from this Merge function, the number of nodes in the primary tree is the same as it was before merging. The primary and secondary trees are different. So technically, the primary tree should be augmented. I tested this with gdb and the program is reaching the following code as well:

primary = new node;
      primary->action = secondary->action;
      primary->left = NULL;
      primary->right = NULL;
      primary->leaf = secondary->leaf;

      Merge(primary->left,secondary->left);
      Merge(primary->right,secondary->right);

Which means, a new node is being created. But it doesn't appear on the primary tree when returned from this function. Anyone can help me?

Thanks in advance.

Recommended Answers

All 2 Replies

If you want to modify the pointer primary (which was in either primary->left or primary->right in the recursive caller), you need to pass the pointer by reference. Because modifying primary in the above code snippet is not going to affect the original tree that you pass to Merge. So, simply change the prototype of your Merge function to something like this:

void Merge(node* &primary,node* &secondary)

For the rest, I can't really tell if your function will work before you explain further how your tree is structured.

Thanks a lot Mike. Now it's working perfectly. I forgot the fact that I should pass it by reference because I was passing the pointers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.