Skip to content

Commit eddb31f

Browse files
solves convert sorted array to bst
1 parent 854507c commit eddb31f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
public class ConvertSortedArrayToBinarySearchTree {
2+
private static class TreeNode {
3+
int val;
4+
TreeNode left;
5+
TreeNode right;
6+
7+
TreeNode(int val) {
8+
this.val = val;
9+
}
10+
11+
TreeNode(int val, TreeNode left, TreeNode right) {
12+
this.val = val;
13+
this.left = left;
14+
this.right = right;
15+
}
16+
}
17+
18+
public static TreeNode sortedArrayToBST(int[] array) {
19+
return sortedArrayToBST(array, 0, array.length);
20+
}
21+
22+
public static TreeNode sortedArrayToBST(int[] array, int start, int end) {
23+
if (end - start == 0) {
24+
return null;
25+
}
26+
27+
int mid = start + (end - start) / 2;
28+
TreeNode root = new TreeNode(array[mid]);
29+
root.left = sortedArrayToBST(array, start, mid);
30+
root.right = sortedArrayToBST(array, mid + 1, end);
31+
return root;
32+
}
33+
}

0 commit comments

Comments
 (0)