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.

class Solution {
public:
    void f(vector<int> & v, int start, int end, TreeNode *&root){
        if (start > end){
            return;
        }
        int m = start + (end - start)/2;
        if (!root){
            root = new TreeNode(v[m]);
            f(v,start,m-1,root->left);
            f(v,m+1,end,root->right);
        }
    }
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!head){
            return NULL;
        }
        vector<int> v;
        for(ListNode *p = head; p; p = p->next){
            v.push_back(p->val);
        }
        TreeNode * root = NULL;
        f(v,0,v.size() -1, root);
        return root;
    }
};

 

posted @ 2013-07-01 23:19  一只会思考的猪  阅读(138)  评论(0编辑  收藏  举报