leetcode[109]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.

/**

 * 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 *creatTree(ListNode *&head, int left, int right)

{

    if(left>right)return NULL;

    int mid=(left+right)/2;

    TreeNode *treeLeft=creatTree(head,left,mid-1);

    TreeNode *root=new TreeNode(head->val);    

    root->left=treeLeft;

    head=head->next;

    root->right=creatTree(head,mid+1,right);

}

TreeNode *sortedListToBST(ListNode *head) {

    TreeNode *root;

    int len=0;

    ListNode *tmp=head;

    while(tmp)

    {

        len++;

        tmp=tmp->next;

    }

    root=creatTree(head, 0, len-1);

}

/*

void creatTree(TreeNode *&root,vector<int> &num,int left,int right)

{

    if(left>right)return;

    int mid=(left+right)/2;

    root=new TreeNode(num[mid]);

    creatTree(root->left,num,left,mid-1);

    creatTree(root->right,num,mid+1,right);

}

TreeNode *sortedArrayToBST(vector<int> &num) 

{

    TreeNode *root=NULL;

    creatTree(root,num,0,num.size()-1);

    return root;

}

    TreeNode *sortedListToBST(ListNode *head) {

        TreeNode *root=NULL;

        if(head==NULL)return root;

        vector<int> num;

        while(head)

        {

            num.push_back(head->val);

            head=head->next;

        }

        return sortedArrayToBST(num);

    }

*/

};

 

你可能感兴趣的:(Binary search)