[LeetCode] 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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM