I have no Idea what I'm doing wrong. I have 3 functions to store the data from two binary trees into arrays. My Problem is the following: Everything works fine for arr2 but not for arr1. Does anybody have an idea how to resolve this? Help would be appreciated!
EDIT: The first array looks like it's also containing the values from arr2 and some random numbers.
The first function creates the arrays and calls treeToArray.
void merge(Node* n1, Node* n2){
int l1 = getTreeSize(n1);
cout << "array size " << l1 << endl;
int *arr1 = new int[l1];
int i = 0;
treeToArray(n1, arr1, i); //This array is not filled how it's supposed to be.
int l2 = getTreeSize(n2);
cout << "array size " << l2 << endl;
int *arr2 = new int[l2]; //corrected this, thanks!
int j = 0;
treeToArray(n2, arr2, j);
for(int i = 0; i < l1; ++i)
cout << "array" << arr1[i] << " ";
merge(arr1, arr2, l1, l2);
}
treeToArray is supposed to store the Tree's data into the array.
void treeToArray(Node* n, int values[], int index) {
if(n == NULL)
return;
if(n->left != NULL)
treeToArray(n->left, values, index);
cout << "speichere " << n->data << endl;
values[index] = n->data;
index++;
if(n->right != NULL)
treeToArray(n->right, values, index);
}
And getTreeSize returns the size of the Tree.
int getTreeSize(Node* n) {
if(n == NULL) {
return 0;
} else {
return (getTreeSize(n->left) + getTreeSize(n->right) + 1 ); //
}
}
int *arr2 = new int[3];in themergefunction?n1andn2?n1andn2? Since you did the same operations of the two parameters, there must be some difference between these two parameters. And intreeToArray(), theindexof left node will be the same as current node. That might be the reason.