Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
This is similar to sort list and so on. You need to use the fast and slow pointer method to find the midpoint of the linked list, then, use the recursive method to construct the Left and Right sub-trees (divide & conquer is used), and then build the node.
Note the following when programming:
(1) Using Dummy nodes helps you find the prev node in the midpoint
However, the dummy node can only be constructed when it is used. We recommend that you do not create the parameter data transmission in advance, which is very unclear. After the operation, remember Delete. Otherwise, the memory leak cannot be deleted too early, because Prev may be equal to dummy.
(2) Boundary Condition
When the middle node is head, note that the Left subtree is null and do not build recursively.
Code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode *sortedListToBST(ListNode *head) { if(!head) return NULL; TreeNode* treeHead = buildTree(head); return treeHead; } TreeNode* buildTree(ListNode *head) { if(!head) return NULL; if(!head->next) return new TreeNode(head->val); ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* prev = dummy, *slow = dummy->next, *fast = dummy->next->next; while(fast && fast->next) { slow = slow->next; prev = prev->next; fast = fast->next->next; } TreeNode* cur = new TreeNode(slow->val); TreeNode* left, *right; // second error, cannot initialize left in the if-else right = buildTree(slow->next); if(prev != dummy) // first error { prev->next = NULL; left = buildTree(head); } else left = NULL; cur->left = left; cur->right = right; delete dummy; // first error, can not delete dummy too early if prev equals dummy return cur; }};
5 convert sorted list to binary search tree_leetcode