Array to BST | Practice | GeeksforGeeks

Given a sorted array. Convert it into a Height balanced Binary Search Tree (BST). Find the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.
Height balanced BST means a binary tree in which the depth of the left subtree and the right subtree of every node never differ by more than 1.
Example 1:
Input: nums = {1, 2, 3, 4}
Output: {2, 1, 3, 4}
Explanation: 
The preorder traversal of the following 
BST formed is {2, 1, 3, 4}:
           2
         /   \
           1     3
               \
                4

 
Example 2:
Input: nums = {1,2,3,4,5,6,7}
Ouput: {4,2,1,3,6,5,7}
Explanation: 
The preorder traversal of the following
BST formed is {4,2,1,3,6,5,7} :
        4
       / \
      2   6
     / \  / \
    1   3 5  7

 
Your Task:
You don't need to read or print anything. Your task is to complete the function sortedArrayToBST() which takes the sorted array nums as input paramater and returns the preorder traversal of height balanced BST. If there exist many such balanced BST consider the tree whose preorder is lexicographically smallest.
Expected Time Complexity: O(n)
Expected Space Complexity: O(n)
Constraints:
1 ≤ |nums| ≤ 104
-104 ≤ nums[i] ≤ 104
 
0
singhkrish14141 week ago
class Node:
   def __init__(self, value):
       self.data = value
       self.left = None
       self.right = None
class Solution:
   def sortedArrayToBST_helper(self, array):
       if not array:
           return None
       mid =(len(array)-1)//2
       node = Node(array[mid])
       node.left = self.sortedArrayToBST_helper(array[:mid])
       node.right = self.sortedArrayToBST_helper(array[mid+1:])
       return node
   def pre_order_traversal(self, root, mapper=[]):
       if root is None:
           return
       map_ = mapper
       map_.append(root.data)
       self.pre_order_traversal(root.left, map_)
       self.pre_order_traversal(root.right, map_)
       return map_
   def sortedArrayToBST(self, array):
       root = self.sortedArrayToBST_helper(array)
       return self.pre_order_traversal(root)
Input
2 
-8 4
 
my output
1 -2 -5 -2 1 1 5 7 -8 4
 
correct output
-8 4
 
when I ran my code with the set of value in custom input it return the output -8 4 but when I submit the code I am getting different output, can anyone tell me what's wrong in my code.
 
 
0
amishasahu3282 weeks ago
class Solution {
public:
    void convertToBST(vector<int> &nums, int start, int end, vector<int> &preorder)
    {
        if(start > end) return;
        int mid = (start + end) >> 1;
        preorder.push_back(nums[mid]);
        convertToBST(nums, start, mid-1, preorder);
        convertToBST(nums, mid+1, end, preorder);
    }
    vector<int> sortedArrayToBST(vector<int>& nums) {
        // Code here
        vector<int> preorder;
        convertToBST(nums, 0, nums.size()-1, preorder);
        return preorder;
    }
};

0
adityagagtiwari3 weeks ago
Hello fellas !
Can anyone tell me why cant we make idx variable used below as a normal int type.
I know that the value stored in int datatype gets corrupted across methods but why does this dont apply to other int variables(low and mid) below!!
 
class Solution
{
   public int[] sortedArrayToBST(int[] nums)
   {
       // Code here 
       int[] bst = new int[nums.length];
       int[] idx = new int[1];
       makeATree(0,nums.length-1,nums,bst,idx);
       return bst;
   }
   public void makeATree(int low,int high,int[] nums,int[] bst,int[] k)
   {
       if(low>high)
       return;
       
       int mid = (high+low)/2;
       bst[k[0]]=nums[mid];
       k[0]++;
       makeATree(low,mid-1,nums,bst,k);
       makeATree(mid+1,high,nums,bst,k);
   }
}
0
tanashah
This comment was deleted.
+7
sarthakjagetiya10011 month ago
Total Time Taken:  1.2/2.1
C++
void preorder(vector<int> nums, int s, int e, vector<int> &ans){
        if(s>e){
            return;
        }
        int mid= (s+e)/2;
        ans.push_back(nums[mid]);
        preorder(nums, s, mid-1, ans);
        preorder(nums, mid+1, e, ans);
    }
    vector<int> sortedArrayToBST(vector<int>& nums) {
        vector<int> ans;
        int n=nums.size();
        preorder(nums, 0, n-1, ans);
        return ans;
    }
+1
lindan1232 months ago
vector<int> vec;
void help(vector<int>& nums,int i,int j)
{
    if(i>j)return;
    
    int mid = (i+j)/2;
    vec.push_back(nums[mid]);
    help(nums,i,mid-1);
    help(nums,mid+1,j);
}
    vector<int> sortedArrayToBST(vector<int>& nums) {
        help(nums,0,nums.size()-1);
        return vec;
    }
Time Taken : 0.2sec
Cpp
+4
ninja_112 months ago
Hint : This is not BST as some of its test cases have duplicate value.
+2
badgujarsachin833 months ago
void preorder(vector<int> &nums,int i,int j,vector<int> &v){
        if(i<=j){
            int mid=(i+j)/2;
            v.push_back(nums[mid]);
            preorder(nums,i,mid-1,v);
            preorder(nums,mid+1,j,v);
        }
    }
    vector<int> sortedArrayToBST(vector<int>& nums) {
        // Code here
        vector<int> v;
        int i=0,j=nums.size()-1;
        preorder(nums,i,j,v);
        return v;
    }
0
krishnagautam58994 months ago
struct Node{      int data;   struct Node *left;   struct Node *right;      Node(int x){       data=x;       left=NULL;       right=NULL;   }};
   void solve(vector<int> &nums, vector<int> &ans , int l, int h)   {       if(l>h)       return;              int mid = (l+h) / 2;       int temp = nums[mid];       ans.push_back(temp);              solve(nums,ans,l,mid-1);       solve(nums,ans,mid+1,h);   }   vector<int> sortedArrayToBST(vector<int>& nums) {              vector<int>ans;       int l = 0;       int h = nums.size()-1;       solve(nums,ans,l,h);       return ans;   }
-1
jmonu1327 months ago
 void bstbuild(vector<int> nums,vector<int> &v,int si,int ei)   {       if(si<=ei)       {         int mid=(si+ei)/2;         v.push_back(nums[mid]);         bstbuild(nums,v,si,mid-1);         bstbuild(nums,v,mid+1,ei);       }   }   vector<int> sortedArrayToBST(vector<int>& nums) {       // Code here       vector<int> v;       int si=0,ei=nums.size()-1;       bstbuild(nums,v,si,ei);       return v;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.