I'm trying to convert a BST to an Array.
void treeToArr(Node *root, int *ptr, int index)
{
if (root == NULL) {
return;
}
storeInArray(root->left,ptr,index);
ptr[index ] = root->value;
storeInArray(root->right,ptr,index);
}
When running this, I noticed that the index number kept changing, it went from 0 to 1 to 0 to 1 to 2 to 3. I just want it to increase normally [1,2,3,4..]. I'm new to C and i'm unsure why it's doing this.
Note that when I call this function, index is 0.
CodePudding user response:
You need to pass a pointer to index instead of index itself. That way, index will be modified across all recursive calls.
CodePudding user response:
It's one thing to pass values 'down' in recursive calls.
You could use a pointer to a single instance of an int index;
that exists in the top level caller.
Or, you could return to 'parent nodes' what the child nodes have done with the value.
int treeToArr(Node *root, int *ptr, int index)
{
if (root == NULL)
return index;
index = storeInArray(root->left,ptr,index);
ptr[index ] = root->value;
return storeInArray(root->right,ptr,index);
}