C++實現(xiàn)LeetCode(109.將有序鏈表轉(zhuǎn)為二叉搜索樹)
[LeetCode] 109.Convert Sorted List to Binary Search Tree 將有序鏈表轉(zhuǎn)為二叉搜索樹
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
這道題是要求把有序鏈表轉(zhuǎn)為二叉搜索樹,和之前那道 Convert Sorted Array to Binary Search Tree 思路完全一樣,只不過是操作的數(shù)據(jù)類型有所差別,一個是數(shù)組,一個是鏈表。數(shù)組方便就方便在可以通過index直接訪問任意一個元素,而鏈表不行。由于二分查找法每次需要找到中點,而鏈表的查找中間點可以通過快慢指針來操作,可參見之前的兩篇博客 Reorder List 和 Linked List Cycle II 有關(guān)快慢指針的應用。找到中點后,要以中點的值建立一個數(shù)的根節(jié)點,然后需要把原鏈表斷開,分為前后兩個鏈表,都不能包含原中節(jié)點,然后再分別對這兩個鏈表遞歸調(diào)用原函數(shù),分別連上左右子節(jié)點即可。代碼如下:
解法一:
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; } };
我們也可以采用如下的遞歸方法,重寫一個遞歸函數(shù),有兩個輸入?yún)?shù),子鏈表的起點和終點,因為知道了這兩個點,鏈表的范圍就可以確定了,而直接將中間部分轉(zhuǎn)換為二叉搜索樹即可,遞歸函數(shù)中的內(nèi)容跟上面解法中的極其相似,參見代碼如下:
解法二:
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/
到此這篇關(guān)于C++實現(xiàn)LeetCode(109.將有序鏈表轉(zhuǎn)為二叉搜索樹)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)將有序鏈表轉(zhuǎn)為二叉搜索樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++數(shù)據(jù)結(jié)構(gòu)二叉搜索樹的實現(xiàn)應用與分析
- C++實現(xiàn)LeetCode(173.二叉搜索樹迭代器)
- C++實現(xiàn)LeetCode(108.將有序數(shù)組轉(zhuǎn)為二叉搜索樹)
- C++實現(xiàn)LeetCode(99.復原二叉搜索樹)
- C++實現(xiàn)LeetCode(98.驗證二叉搜索樹)
- C++實現(xiàn)LeetCode(96.獨一無二的二叉搜索樹)
- C++實現(xiàn)LeetCode(95.獨一無二的二叉搜索樹之二)
- C++ 二叉搜索樹(BST)的實現(xiàn)方法
- C++ 超詳細快速掌握二叉搜索樹
相關(guān)文章
C語言中判斷素數(shù)(求素數(shù))的思路與方法實例
計算機或者相關(guān)專業(yè)基本上大一新生開始學編程都會接觸的一個問題就是判斷質(zhì)數(shù),下面這篇文章主要給大家介紹了關(guān)于C語言中判斷素數(shù)(求素數(shù))的思路與方法,需要的朋友可以參考下2022-03-03OPENMP?SECTIONS?CONSTRUCT原理示例解析
這篇文章主要為大家介紹了OPENMP?SECTIONS?CONSTRUCT原理示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03