Construct BST
Send Feedback
Given a sorted integer array A of size n which contains all unique elements. You need to construct a balanced BST from this input array. Return the root of constructed BST.
Note : If array size is even, take first mid as root.
Input format :
Output Format :
Sample Input :
Sample Output :
- public class Solution {
- /* Binary Tree Node class
- *
- * class BinaryTreeNode<T> {
- T data;
- BinaryTreeNode<T> left;
- BinaryTreeNode<T> right;
- public BinaryTreeNode(T data) {
- this.data = data;
- }
- }
- */
- private static BinaryTreeNode<Integer> makeBstFromSortedArray(int[] arr,int start, int end) {
- if(start>end)
- {
- return null;
- }
- int mid = (start+end)/2;
- BinaryTreeNode<Integer> root = new BinaryTreeNode<>(arr[mid]);
- //Now we will make left side of Bst
- BinaryTreeNode<Integer> left = makeBstFromSortedArray(arr,start,mid-1);
- //Now we will make right sider of binary search tree
- BinaryTreeNode<Integer> right = makeBstFromSortedArray(arr,mid+1,end);
- root.left = left;
- root.right = right;
- return root;
- }
- public static BinaryTreeNode<Integer> SortedArrayToBST(int[] arr){
- int start = 0;
- int end = arr.length-1;
- return makeBstFromSortedArray(arr,start,end);
- }
- }
No comments:
Post a Comment