Click to See Complete Forum and Search --> : duplicating a tree


chickenandfries
February 1st, 2008, 08:49 AM
I'm trying to duplicate a binary tree with the following code:

treeNode* copy(treeNode *root) {
treeNode *dupRoot, *dupLeft, *dupRight;
if (root!=NULL) {
dupLeft=copy(root->left);
dupRight=copy(root->right);
dupRoot=(treeNode *)malloc(sizeof(treeNode));
dupRoot->data=root->data;
dupRoot->left=dupLeft;
dupRoot->right=dupRight;
}
return dupRoot;
}

When I use this function, it successfully duplicates the tree but the left and right sons of the leaves do not point to NULL. How do I modify the code to make the sons of the leaves point to NULL?

TheCPUWizard
February 1st, 2008, 09:12 AM
Please show your declaration and constructor implementations for "treeNode"..

chickenandfries
February 1st, 2008, 10:02 AM
I've done it! The code should have been:

treeNode* copy(treeNode *root) {
treeNode *dupRoot=NULL, *dupLeft, *dupRight;
if (root!=NULL) {
dupLeft=copy(root->left);
dupRight=copy(root->right);
dupRoot=(treeNode *)malloc(sizeof(treeNode));
dupRoot->data=root->data;
dupRoot->left=dupLeft;
dupRoot->right=dupRight;
}
return dupRoot;
}

Thanks anyway.