Thursday, September 25, 2014

[Leetcode] Convert Sorted Array to Binary Search Tree

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

Analysis:

class Solution {
public:

    TreeNode *helper(vector &num, int b, int e) {
        if (b > e)
            return NULL;
        else
        {
            //middle as the root and recursively to construct the tree left and right
            int mid = (b+e)/2;
            TreeNode* root = new TreeNode(num[mid]);
            root->left = helper(num, b, mid - 1);
            root->right = helper(num, mid+1, e);
            return root;
        }
    }

    TreeNode *sortedArrayToBST(vector &num) {
        return helper(num, 0, num.size() - 1);
    }
};

No comments:

Post a Comment