Pregunta de entrevista de Microsoft

Given a sorted array, write a function that will create a binary search tree from the array.

Respuestas de entrevistas

Anónimo

18 de dic de 2014

Make the middle element of the array the root and have the function return the root. recursively call the function for the left subarray and right subarray to make the left and right subtrees.

Anónimo

15 de ene de 2015

As Described above in code ;) //Tree Node class node{ int data; node left; node right; public node(){ left = null; right = null; } public node(int d){ data = d; left = null; right = null; } }; public static node makeBST(int[] arr,int start, int end){ if(start > end){ return null; } int mid = (start + end)/2; node root= new node(arr[mid]); root.left = makeBST(arr, start, mid - 1); root.right = makeBST(arr, mid + 1, end); return root; } public static node createBST(int arr[]){ if(arr.length > 0){ return makeBST(arr, 0, arr.length); } else{ return null; } }