Array to BST (Proper Comments)

soham0047

Soham

Posted on May 27, 2022

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.

💖 💪 🙅 🚩
soham0047
Soham

Posted on May 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024