2021年3月30日星期二

Store tree structured data to an array in C

I am trying to write a code to transverse a tree data structure using inorder transversal and store all the nodes onto an array.

I came up with this code below but it doesn't work, as the index of any previous recursion has already been passed on in the function.

int *inorderTransversal(AVLTreeNode *node, AVLTreeNode *array[], int index)  {      if (node == NULL)          return index;        inorderTransversal(node->left, treeSize);      nodesArray[index] = node;      index++;      inorderTransversal(node->right, treeSize);      return index;   }  

I know I could possibly declare a static 'index' value inside the function, and it might work? But the downside is it makes 'index' stays in the memory for the entire duration of the program e.g.

void *inorderTransversal(AVLTreeNode *node, AVLTreeNode *array[])  {      static int index = 0;      if (node == NULL)          return;        inorderTransversal(node->left, array);      nodesArray[index] = node;      index++;      inorderTransversal(node->right, array);      return;   }  

Or I could declare the array outside the function prior? e.g.

AVLTreeNode *array[tree->size];   int index = 0;     void *inorderTransversal(AVLTreeNode *node) {       if (node == null)           return;         inorderTransversal(node->left);       array[index] = node;       index++;      inorderTransversal(node->right);   }   

Could someone help me to amend the code to include the 'index' increments inside the function without using static? Much appreciated!

https://stackoverflow.com/questions/66880704/store-tree-structured-data-to-an-array-in-c March 31, 2021 at 10:07AM

没有评论:

发表评论