I have tried implementing the code for Sorted Linked List to BST from leetcode https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ .
The approach which I have used to use a recursive approach like below. But here we have to use reference (&) in head in the function argument. If I don't use, then output will not be correct and gives wrong answer. I am not able to grasp why reference to head is needed here or in what type of recursion scenarios we should do that. I sometimes get confused in recursion.
int countNodes(ListNode* head) {
int count = 0;
ListNode *temp = head;
while (temp != NULL) {
temp = temp->next;
count++;
}
return count;
}
TreeNode *sortedListUtil(ListNode *&head, int n) {
// head should be ref, if we dont use & ,
// unexpected output will come
if (n <= 0)
return NULL;
TreeNode *left = sortedListUtil(head, n/2);
TreeNode *root = new TreeNode(head->val);
root->left = left;
head = head->next;
root->right = sortedListUtil(head, n - n/2 -1);
// recur for remaining nodes
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
if (head == NULL)
return NULL;
int n = countNodes(head);
return sortedListUtil(head, n);
}
Input linked List is : head = [-10,-3,0,5,9]
Output of BST should be this if I use & in head in function argument : [0,-3,9,-10,null,5]
If I don't use '&' in function argument then the tree constructed will be :
[-10,-10,-3,-10,null,-3] which is wrong. Root Node should be 0.