Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.html
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.node
Example:數組
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
這道題是要求把有序鏈表轉爲二叉搜索樹,和以前那道 Convert Sorted Array to Binary Search Tree 思路徹底同樣,只不過是操做的數據類型有所差異,一個是數組,一個是鏈表。數組方便就方便在能夠經過index直接訪問任意一個元素,而鏈表不行。因爲二分查找法每次須要找到中點,而鏈表的查找中間點能夠經過快慢指針來操做,可參見以前的兩篇博客 Reorder List 和 Linked List Cycle II 有關快慢指針的應用。找到中點後,要以中點的值創建一個數的根節點,而後須要把原鏈表斷開,分爲先後兩個鏈表,都不能包含原中節點,而後再分別對這兩個鏈表遞歸調用原函數,分別連上左右子節點便可。代碼以下:
函數
解法一:post
class Solution { public: TreeNode *sortedListToBST(ListNode* head) { if (!head) return NULL; if (!head->next) return new TreeNode(head->val); ListNode *slow = head, *fast = head, *last = slow; while (fast->next && fast->next->next) { last = slow; slow = slow->next; fast = fast->next->next; } fast = slow->next; last->next = NULL; TreeNode *cur = new TreeNode(slow->val); if (head != slow) cur->left = sortedListToBST(head); cur->right = sortedListToBST(fast); return cur; } };
咱們也能夠採用以下的遞歸方法,重寫一個遞歸函數,有兩個輸入參數,子鏈表的起點和終點,由於知道了這兩個點,鏈表的範圍就能夠肯定了,而直接將中間部分轉換爲二叉搜索樹便可,遞歸函數中的內容跟上面解法中的極其類似,參見代碼以下:this
解法二:url
class Solution { public: TreeNode* sortedListToBST(ListNode* head) { if (!head) return NULL; return helper(head, NULL); } TreeNode* helper(ListNode* head, ListNode* tail) { if (head == tail) return NULL; ListNode *slow = head, *fast = head; while (fast != tail && fast->next != tail) { slow = slow->next; fast = fast->next->next; } TreeNode *cur = new TreeNode(slow->val); cur->left = helper(head, slow); cur->right = helper(slow->next, tail); return cur; } };
相似題目:spa
Convert Sorted Array to Binary Search Tree指針
參考資料:code
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/