Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.編程
這題和sort list等題都比較類似,須要先用快慢指針的方法找到鏈表的中點,而後用recursive的方式構建左子樹和右子樹(用到的思想是Divide&Conquer),而後再構建好這個節點。ide
編程時一點要注意:ui
(1)dummy節點的使用能夠幫助找到中點的prev節點spa
可是dummy節點只有當用時再構造,建議不要提早建好當參數傳進來,會很是不清晰。用完後最後記得delete,不然會memory leak. 也不能delete得過早,由於prev可能等於dummy.指針
(2)邊界狀況blog
當middle節點爲head時,應注意,左子樹爲NULL,不要遞歸build。遞歸
Code:element
/** * 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; } };