Convert Sorted Array to Binary Search Tree @LeetCode

PROBLEM :

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

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Recursive Solution )
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

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

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :(Iterative Solution - using divide-and-conquer )
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

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

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )