sourcecode

Saturday, November 24, 2012

Convert Sorted Array to Binary Search Tree

http://www.leetcode.com/onlinejudge

/**passed both small and large judges.
Pretty straight forward: binary search like method.
Using the center element as the root, and recurse.
 * 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* build(vector<int> const num, int const first, int const last){
        if (first > last) return NULL;
        int const center = (first+last)/2;
        TreeNode* root = new TreeNode(num[center]);
        if (first == last) return root;
        root->left = build(num, first, center-1);
        root->right = build(num, center+1,last);
        return root;
    }
    TreeNode *sortedArrayToBST(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return build(num,0,num.size()-1);
    }
};

No comments: