Leetcode Convert Sorted Array to Binary Search Tree

OpenSoucre發表於2014-06-23

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

TreeNode *createSearchTree(vector<int>& num, int left , int right){
    if(left > right) return NULL;
    int mid = (left+right)>>1;
    TreeNode *root = new TreeNode(num[mid]);
    root->left = createSearchTree(num,left,mid-1);
    root->right = createSearchTree(num,mid+1,right);
    return root;
}

TreeNode *sortedArrayToBST(vector<int> &num) {
    return createSearchTree(num,0,num.size()-1);
}

 

相關文章