Convert Sorted Array to Binary Search Tree

Given an array 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 *sortedArrayToBST(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!num.size()){
            return NULL;
        }
        TreeNode * root = NULL;
        f(num,0,num.size() -1, root);
        return root;
    }
};

 

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