109. Convert Sorted List to Binary Search Tree(根据有序链表构造平衡的二叉查找树)

题意:根据有序链表构造平衡的二叉查找树。

/**
 * 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;
        if(head -> next == NULL) return new TreeNode(head -> val);
        ListNode *fast = head;
        ListNode *slow = head;
        ListNode *pre;
        while(fast && fast -> next){
            fast = fast -> next -> next;
            pre = slow;
            slow = slow -> next;
        }
        pre -> next = NULL;
        TreeNode *root = new TreeNode(slow -> val);
        root -> left = sortedListToBST(head);
        root -> right = sortedListToBST(slow -> next);
        return root;
    }
};

  

posted @ 2020-03-25 21:48  Somnuspoppy  阅读(109)  评论(0编辑  收藏  举报