Search code examples
cbinary-treebinary-search-treebinary-search

How to reset static variable or how to create the get_length function for a binary tree?


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.


Solution

  • 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);
       }
    }