You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
3
+
Note: If array size is even, take first mid as root.
4
+
5
+
Input format:
6
+
The first line of input contains an integer, which denotes the value of n. The following line contains n space separated integers, that denote the values of array.
7
+
8
+
Output Format:
9
+
The first and only line of output contains values of BST nodes, printed in pre order traversal.
10
+
11
+
Constraints:
12
+
Time Limit: 1 second
13
+
14
+
Sample Input 1:
15
+
7
16
+
1 2 3 4 5 6 7
17
+
Sample Output 1:
18
+
4 2 1 3 6 5 7
19
+
*/
20
+
public class Solution {
21
+
22
+
/* Binary Tree Node class
23
+
*
24
+
* class BinaryTreeNode<T> {
25
+
T data;
26
+
BinaryTreeNode<T> left;
27
+
BinaryTreeNode<T> right;
28
+
29
+
public BinaryTreeNode(T data) {
30
+
this.data = data;
31
+
}
32
+
}
33
+
*/
34
+
35
+
public static BinaryTreeNode<Integer> SortedArrayToBST(int[] arr, int n){
36
+
return SortedArrayToBSTHelper(arr,0,n-1);
37
+
38
+
}
39
+
40
+
public static BinaryTreeNode<Integer> SortedArrayToBSTHelper(int[] arr, int si, int ei){
41
+
if (si>ei)
42
+
return null;
43
+
44
+
int mid=(si+ei)/2;
45
+
BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>(arr[mid]);
0 commit comments