C++ - BST Operations, Copy Only Even Nodes

I'm trying to modify my code to copy a BST to only copy even data.
I'm having some problems with trying to manage recursive calls...

Here's my function for copying the whole list, which works fine.
1
2
3
4
5
6
7
8
9
10
11
12
node* copyBST(node*root)
{
  node *copyNode = NULL;
  if(root){
    copyNode = new node;
    copyNode->data = root->data;
    copyNode->left = copyBST(root->left);
    copyNode->right = copyBST(root->right);
  }
  
  return copyNode;
}


Here's my function for copying even data, which doesn't work... it seg faults.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
node* copyEven(node*root)
{
  node *copyNode = NULL;
  if(root && root->data % 2 == 0){
    copyNode = new node;
    copyNode->data = root->data;
    copyNode->left = copyEven(root->left);
    copyNode->right = copyEven(root->right);
  }
  else{
    copyNode->left = copyEven(root->left);
    copyNode->right = copyEven(root->right);
  }
  
  return copyNode;
}


Any help would be appreciated.
It segfaults since you access copyNode and root even when they are NULL. However, you probably need to go about it in a different (and simpler) way.

The way you do copyBST works since you are copying every node. But if you leave some nodes out it doesn't work so well. Consider what would happen if the root needed to be left out. Then one of the children would need to be upgraded to root. The output tree would have a different structure than the input tree and you can't use the recursive traversal pattern of the input to guide the assembly of the output anymore.

The best thing to do is to do a normal recursive traversal of the tree and pass in a reference to the new tree to insert the even nodes into.
Last edited on
Topic archived. No new replies allowed.