C++實現LeetCode(109.將有序鏈表轉為二叉搜索樹)
[LeetCode] 109.Convert Sorted List to Binary Search Tree 將有序鏈表轉為二叉搜索樹
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
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.
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 有關快慢指針的應用。找到中點後,要以中點的值建立一個數的根節點,然後需要把原鏈表斷開,分為前後兩個鏈表,都不能包含原中節點,然後再分別對這兩個鏈表遞歸調用原函數,分別連上左右子節點即可。代碼如下:
解法一:
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; } };
我們也可以采用如下的遞歸方法,重寫一個遞歸函數,有兩個輸入參數,子鏈表的起點和終點,因為知道瞭這兩個點,鏈表的范圍就可以確定瞭,而直接將中間部分轉換為二叉搜索樹即可,遞歸函數中的內容跟上面解法中的極其相似,參見代碼如下:
解法二:
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; } };
類似題目:
Convert Sorted Array to Binary Search Tree
參考資料:
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/35476/Share-my-JAVA-solution-1ms-very-short-and-concise.
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/35470/Recursive-BST-construction-using-slow-fast-traversal-on-linked-list
到此這篇關於C++實現LeetCode(109.將有序鏈表轉為二叉搜索樹)的文章就介紹到這瞭,更多相關C++實現將有序鏈表轉為二叉搜索樹內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!