## Amazon Interview Question

SDE-2s**Country:**India

**Interview Type:**Phone Interview

1. Get the middle item in the array and create a node.

2. Call this method again with the array on the left side of the middle element - assign the node to left.

3. Call this method again with the array on the right side of the middle element - assign the returned node to right.

4. return the node.

```
#include<stdio.h>
#include<stdlib.h>
struct TNode
{
int data;
struct TNode* left;
struct TNode* right;
};
struct TNode* newNode(int data);
struct TNode* sortedArrayToBST(int arr[], int start, int end)
{
if (start > end)
return NULL;
int mid = (start + end)/2;
struct TNode *root = newNode(arr[mid]);
root->left = sortedArrayToBST(arr, start, mid-1);
root->right = sortedArrayToBST(arr, mid+1, end);
return root;
}
struct TNode* newNode(int data)
{
struct TNode* node = (struct TNode*)
malloc(sizeof(struct TNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void preOrder(struct TNode* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
int n = sizeof(arr)/sizeof(arr[0]);
struct TNode *root = sortedArrayToBST(arr, 0, n-1);
printf("\n PreOrder Traversal of constructed BST ");
preOrder(root);
return 0;
}
```

The solution is simple as they didn't say abt the "BST" is balanced or not ...

so let us take the array is sorted in ascending order

Now keep adding all the elements to the right of the nodes

eg : {1,2,3,4,5}

node(1).right->node(2).right->node(3).right->node(4).right->node(5)

all node(x).left->null

this is also a BST :-)

```
private static void PreOrder(TreeClass tree)
{
if (tree != null)
{
Console.Write(tree.Data);
PreOrder(tree.Left);
PreOrder(tree.Right);
}
}
private static TreeClass ArrayToTree(int[] sortedArr, int start, int end)
{
if (start > end)
return null;
int mid = (start + end)/2;
return new TreeClass
{
Data = sortedArr[mid],
Left = ArrayToTree(sortedArr, start, mid - 1),
Right = ArrayToTree(sortedArr, mid + 1, end)
};
}
private class TreeClass
{
private TreeClass _left;
private TreeClass _right;
private int _data;
public TreeClass Left
{
get { return _left; }
set { _left = value; }
}
public TreeClass Right
{
get { return _right; }
set { _right = value; }
}
public int Data
{
get { return _data; }
set { _data = value; }
}
```

}

Assuming there is Node class ready

```
public static Node createBSTFromSorted(int[] arr) {
if (arr.length > 0) return createBSTAux(arr, 0, arr.length-1);
else return null;
}
private static Node createBSTAux(int[] arr, int front, int end) {
if (front > end) return null;
int middle = front + (end - front) / 2;
Node head = new Node(arr[middle]);
head.left = createBSTAux(arr, front, middle-1);
head.right = createBSTAux(arr, middle+1, end);
return head;
}
```

- shukad333 October 05, 2014