Pergunta de entrevista da empresa Microsoft

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

Respostas da entrevista

Sigiloso

18 de dez. 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.

Sigiloso

15 de jan. 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; } }