LeetCode ---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:
    void ListToBst(ListNode* &head,TreeNode* &root)
    {
        if(head==NULL)
            return ;
        ListNode *slow=head;
        ListNode *fast=head;
        ListNode *cur=head;
        int i=0;
        while(fast->next!=NULL)
        {
            if(fast->next->next!=NULL)
            {
                fast=fast->next->next;
                cur=slow;
                slow=slow->next;
            }
            else{
                cur=slow;
                fast=fast->next;
                slow=slow->next;
                 
            }
            i++;
        }
        root=new TreeNode(slow->val);
        if(i==0)
            return;
        cur->next=NULL;
        ListToBst(head, root->left);
        ListToBst(slow->next, root->right);
    }
    TreeNode* sortedListToBST(ListNode* head) {
        if(head==NULL)
            return NULL;
        TreeNode *root=NULL;
        ListToBst(head,root);
        return root;
    }
};

你可能感兴趣的:(LeetCode ---Convert Sorted List to Binary Search Tree)