如何重置静态变量或如何为二叉树创建get_length函数?

我决定将数组存储到二叉树中,因此,数组的所有元素都位于树的右侧。如何计算所有这些元素?

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 reseted and returned length is incorrect. After each usage a variable will be increased.

评论
  • Lee
    Lee 回复

    我建议通过镜头:

    int get_length(Node * array, int len) {
       if (array == NULL) return len;
       else {
           return get_length(array->right, len + 1);
       }
    }