```
int getListLength(ListNode *head)
{
ListNode *p = head;
int length = 0;
while(p != NULL) {
p = p ->next;
length++;
}
return length;
}
TreeNode *sortedListToBST(ListNode **head, int start, int right)
{
if(start > right) {
return NULL;
}
int mid = (start + right) / 2;
TreeNode *leftTree = sortedListToBST(head, start, mid - 1);
TreeNode *root;
root ->val = (*head) ->val;
*head = (*head) ->next;
TreeNode *rightTree = sortedListToBST(head, mid + 1, right);
root ->left = leftTree;
root ->right = rightTree;
return root;
}
TreeNode *sortedListToBST(ListNode *head)
{
int length = getListLength(head);
if(length <= 0) return NULL;
return sortedListToBST(&head, 0, length - 1);
}
```

My Code has a bug for bad memory access.

In the function sortedListToBST(ListNode **head, int start, int right), line 7, who assign the node's value to the root node, (*head) ->val.

In my XCode, I could see everything in the memory block when in debug mode, however the code just could not access the memory and assign value after 1 or 2 recursion.

Can someone help me to fix this problem? Thank you!