I've decided to store an array into a binary tree, so that all elements of array locate on right side of tree. How to count all of these elements?
int get_length(Node * array) {
static int len = 0;
if (array == NULL) return len;
else {
len++;
get_length(array->right);
}
}
Problem in static variable: after each usage of this function, variable len
is not reset and the returned length is incorrect. After each usage that variable will be increased.
Don't use static
. Accumulate the return value of the recursive call. For example:
int get_length(Node * array) {
if (array == NULL) return 0;
else {
return 1+get_length(array->right);
}
}