Skip to content

Commit 80d9fc6

Browse files
authored
Create Construct BST
1 parent c84c95e commit 80d9fc6

File tree

1 file changed

+52
-0
lines changed
  • Course 2 - Data Structures in JAVA/Lecture 13 - BST I

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
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]);
46+
47+
root.left=SortedArrayToBSTHelper(arr,si,mid-1);
48+
root.right=SortedArrayToBSTHelper(arr,mid+1,ei);
49+
return root;
50+
51+
}
52+
}

0 commit comments

Comments
 (0)