109. Convert Sorted List to Binary Search Tree

image.png

题解一:类似二分查找,借助快慢指针找中点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head){
        if(head == NULL) return NULL;
        return helper(head,NULL);
    }
private:
    ListNode* findMidNode(ListNode* head, ListNode* tail){
        if(head == tail) return NULL;
        if(head->next == tail) return head;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(fast != tail && fast->next != tail){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    TreeNode* helper(ListNode* head, ListNode* tail){
        if(head == tail) return NULL;
        if(head->next == tail) return new TreeNode(head->val);
        ListNode* mid = findMidNode(head, tail);
        ListNode* right = mid->next;
        TreeNode* root = new TreeNode(mid->val);
        cout<<mid->val<<endl;
        root->left = helper(head,mid);
        root->right = helper(right, tail);
        return root;
    }
};

题解二:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(head == NULL) return NULL;
        return helper(head,  NULL);
    }
private:
    TreeNode* helper(ListNode* head, ListNode* tail){
        if(head == tail) return NULL;
        if(head->next == tail) return new TreeNode(head->val);
        ListNode* mid = head, *fast = head;
        while(fast != tail && fast->next != tail){//要注意这里是 *!= tail*
            mid = mid->next;
            fast = fast->next->next;
        }
        TreeNode* root = new TreeNode(mid->val);
        cout<<mid->val<<endl;
        root->left = helper(head, mid);
        root->right = helper(mid->next, tail);
        return root;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容