Tuesday, October 7, 2014

Convert Sorted Array to Binary Search Tree

 // the code is similar to Unique Binary Search Trees II
class Solution {
public:
    TreeNode *sortedArrayToBST2(vector<int> &num,int start,int end) {
        if(start>end)
            return NULL;
        int mid=(start+end)/2;
        TreeNode* root=new TreeNode(num[mid]);
        root->left=sortedArrayToBST2(num,start,mid-1);
        root->right=sortedArrayToBST2(num,mid+1,end);
        return root;
    }
   
    TreeNode *sortedArrayToBST(vector<int> &num) {
        return sortedArrayToBST2(num,0,num.size()-1);
    }
};

No comments:

Post a Comment