Amazon Interview Question
Software Engineer / DevelopersTeam: RCX
Country: United States
Interview Type: In-Person
C#:
public class BSTNode
{
public int data;
public BSTNode left;
public BSTNode right;
}
public BSTNode root;
public void Wrapper(int[] arr)
{
root=BuildBST(arr, 0, arr.Length-1);
}
public BSTNode BuildBST(int[] arr, int lo, int hi)
{
if(lo==hi)
{
return new BSTNode() { data=arr[lo] }; // Using automatic intializer C#
}
int mid=lo + ((hi-lo)/2);
BSTNode node= new BSTNode() { data=arr[mid] };
node.left=BuildBST(arr, lo, mid-1);
node.right=BuildBST(arr, mid+1, hi);
return node;
}
Small correction, for checking edge case:
C#:
public class BSTNode
{
public int data;
public BSTNode left;
public BSTNode right;
}
public BSTNode root;
public void Wrapper(int[] arr)
{
root=BuildBST(arr, 0, arr.Length-1);
}
public BSTNode BuildBST(int[] arr, int lo, int hi)
{
if(lo==hi)
{
return new BSTNode() { data=arr[lo] }; // Using automatic intializer C#
}
int mid=lo + ((hi-lo)/2);
BSTNode node= new BSTNode() { data=arr[mid] };
if(mid!=lo) node.left=BuildBST(arr, lo, mid-1);
node.right=BuildBST(arr, mid+1, hi);
return node;
}
void arraytotree(struct node **root, int array[], int left, int right) {
if(left <= right) {
int mid = (left + right)/2;
insert(root,array[mid]);
arraytotree(root, array, left, mid - 1);
arraytotree(root, array, mid + 1, right);
}
}
void insert(struct node **root, int data) {
if(*root == NULL) {
*root = (struct node *)malloc(sizeof(struct node));
(*root)->left = NULL;
(*root)->right = NULL;
(*root)->data = data;
}
else {
if(data <= (*root)->data)
insert(&((*root)->left),data);
else
insert(&((*root)->right),data);
}
}
If you find any problem with the solution let me know ..
public static Tree createBalancedTreeFromSortedArray(int[] array) {
if(array == null || array.length == 0) {
return null;
}
Node node = createNode(array, 0 , array.length-1);
Tree tree = new Tree();
tree.root = node ;
return tree;
}
private static Node createNode(int[] array, int start, int end) {
int middleElement = (start+end)/2;
System.out.println(start + " : " + end);
int middle = array[middleElement];
Node node = new Node(middle, null, null);
if(start != end && start <= end) {
Node leftnode = createNode(array, start, middleElement-1);
Node rightnode = createNode(array, middleElement+1, end);
node.leftChild = leftnode;
node.rightChild = rightnode;
System.out.println(node + " 's left chick is " + leftnode);
System.out.println(node + " 's right chick is " + rightnode);
} else if(start == end) {
return node ;
} else {
return null;
}
return node;
}
public static void main(String[] args) {
Tree tree = Tree.createBalancedTreeFromSortedArray(new int[]{0, 25, 50, 75, 85, 100, 125, 150});
newNode is the helper function which creates a new node and returns the struct node pointer.
- rkt March 01, 2012