7.Convert Sorted Array to Binary Search Tree

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

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Solution :

Algorithm: * Find the Middle of the array and make it the root * Do it recursively for left and right subtree

class Solution
{
public:
    TreeNode *makeBST(vector<int> &nums, int start, int end)
    {
        if (start > end)
        {
            return NULL;
        }
        int mid = (start + end) / 2;
        TreeNode *root = new TreeNode;
        root->val = nums[mid];
        root->left = makeBST(nums, start, mid - 1);
        root->right = makeBST(nums, mid + 1, end);
        return root;
    }
    TreeNode *sortedArrayToBST(vector<int> &nums)
    {
        TreeNode *t = makeBST(nums, 0, nums.size() - 1);
        return t;
    }
};

Last updated