1

When I call the function newNode an exception is thrown and says stack overflow, I checked the parameters of the node in it says that they can't be read.

             struct node
            {
                int data;
                struct node* left;
                struct node* right;
            };

            //function that initialeze a new node
            struct node* newNode(int data) {
                struct node *node = (struct node *) malloc(sizeof(struct node));
                node->data = data;
                node->left = NULL;
                node->right = NULL;

                return node;
            }

        struct node* arrayToBST(int arr[], int start, int end) {
            int mid = (start + end) / 2;

            struct node *root = newNode(arr[mid]);

            root->left = arrayToBST(arr, start, mid - 1);
            root->right = arrayToBST(arr, start, mid + 1);


            return root;
        }
Hanzla
  • 214
  • 5
  • 15

1 Answers1

1

Function newNode is fine, the real problem is in your function arrayToBST. You are trying to build the tree recursively, but you didn't give it a stop point, for example:

struct node* arrayToBST(int arr[], int start, int end) {
  if (start > end) return NULL;
  int mid = (start + end) / 2;
  ...

Therefore your program will call arrayToBST function endlessly until the stack overflow.

StillFantasy
  • 1,677
  • 9
  • 21