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.

解題思路

升序鏈表轉換成高度平衡的二叉搜索樹,我們只需要找到鏈表的中點當作root然後左右遞歸就可以了。求鏈表中點當然還是用快慢指針了。

C++版代碼實現

/**
 * 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) {
        return toBST(head, NULL);
    }

    TreeNode *toBST(ListNode *head, ListNode *tail){
        if(head == tail)
            return NULL;
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast != tail && fast->next != tail){
            slow = slow->next;
            fast = fast->next->next;
        }
        TreeNode *root = new TreeNode(slow->val);
        root->left = toBST(head, slow);
        root->right = toBST(slow->next, tail);

        return root;
    }
};

系列教程持續發佈中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章