当我尝试为结构分配新指针时出现堆栈溢出错误



当我调用函数newNode抛出异常并说stack overflow时,我检查了其中节点的参数说它们无法读取。

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

函数newNode很好,真正的问题在于你的函数arrayToBST。 您正在尝试递归构建树,但您没有给它一个停止点,例如:

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

因此,您的程序将无休止地调用arrayToBST函数,直到堆栈溢出。