109. Convert Sorted List to Binary Search Tree (search tree constructed from the ordered list balance binary)

Meaning of the questions: search tree based on ordered binary linked list structure balanced.

/**
 * 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;
    }
};

  

Guess you like

Origin www.cnblogs.com/tyty-Somnuspoppy/p/12570809.html