## Amazon Interview Question for SDE1s

Country: United States

Comment hidden because of low score. Click to expand.
1
of 1 vote

``````node *bstree::createTree(int arr[], int start, int end){

if(start > end)
return NULL;
int middle = (start + end)/2;
node *root = createRoot(arr[middle]);
root-> left = createTree(arr, start, middle-1);
root-> right = createTree(arr, middle+1, end);

return root;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Insert middle of array as root.
2. recurse left getting middle of left section, after setting array size to start to middle-1(from step 1).
3. recurse right after setting array to middle+1 to end.

``````node *bstree::createTree(int arr[], int start, int end){

if(start > end)
return NULL;
int middle = (start + end)/2;
node *root = createRoot(arr[middle]);
root-> left = createTree(arr, start, middle-1);
root-> right = createTree(arr, middle+1, end);

return root;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````Working code ::

class Node{
Node left, right;
int data;
Node(int data1){
this.data = data1;
left = null;
right = null;
}

}
public class sortedArrayToBinaryTree {

public Node convert(int[] arr, int start, int end){
if(start > end) {
return null;
}
int mid = (start+end)/2;
Node root = new Node(arr[mid]);
root.left = convert(arr, start, mid-1);
root.right = convert(arr, mid+1, end);

return root;
}

public void display(Node root){

if(root != null) {
display(root.left);
System.out.println(root.data);
display(root.right);
}
}

public static void main(String[] args){
sortedArrayToBinaryTree s = new sortedArrayToBinaryTree();
int[] arr = {1,2,3,4,5,6,7,8,9,10};
Node n = s.convert(arr, 0 , arr.length-1);
System.out.println("Display Tree");
s.display(n);
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public TreeNode toBST(int[] arr){
}

public TreeNode toBSTHelper(int[] arr, int low, int high){
if(low > high)
return null;
int middle = (low + high)/2;
TreeNode root = new TreeNode(arr[middle]);
root.left = toBSTHelper(arr, low, middle-1);
root.right = toBSTHelper(arr, middle+1, high);
return root;
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.