DEV Community

Soham
Soham

Posted on

4 3

Array to BST (Proper Comments)

// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;

 // } Driver Code Ends
class Solution {
public:
//create a helper function
//create a extra vector ds to store the elements
void vectorutility(vector<int>&arr,int low,int high,vector<int>&ds){
    int mid;
//Nothing but to do binary search
    if(low<=high){
        mid = low + (high-low)/2;
        ds.push_back(arr[mid]);
        vectorutility(arr,low,mid-1,ds);
        vectorutility(arr,mid+1,high,ds);
    }
}
//Create main array to bst convertion function
    vector<int> sortedArrayToBST(vector<int>& nums) {
        // Code here

        vector<int>ds;
        vectorutility(nums,0,nums.size()-1,ds);//Utility function that previuosly declared
        return ds;
    }
};

// { Driver Code Starts.
int main(){
    int tc;
    cin >> tc;
    while(tc--){
        int n;
        cin >> n;
        vector<int>nums(n);
        for(int i = 0; i < n; i++)cin >> nums[i];
        Solution obj;
        vector<int>ans = obj.sortedArrayToBST(nums);
        for(auto i: ans)
            cout << i <<" ";
        cout << "\n";
    }
    return 0;
}  // } Driver Code Ends

Enter fullscreen mode Exit fullscreen mode

Hit a 👍 for more such solutions.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay