Problem
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Code
TreeNode *sortedListToBST_r(ListNode *p1,ListNode *p2) { if(p1 == p2) return 0; ListNode *curr1 = p1,*curr2 = p1; while(curr2->next != p2 && curr2->next->next != p2){ curr2 = curr2->next->next; curr1 = curr1->next; } TreeNode *root = new TreeNode(curr1->val); root->left = sortedListToBST_r(p1,curr1); root->right = sortedListToBST_r(curr1->next,p2); return root; } TreeNode *sortedListToBST(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return sortedListToBST_r(head,0); }
No comments:
Post a Comment