Skip to content

Commit 27ca967

Browse files
author
Antesh Sharma
committed
Convert sorted array to balanced BST for faster search and not right/left skewed bst
1 parent 5cd732b commit 27ca967

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.antesh.dsa;
2+
3+
4+
/*Given a sorted array, create a balanced BST and not skewed bst
5+
*
6+
* */
7+
8+
9+
public class SortedArrayToBST {
10+
11+
static class Node {
12+
int data;
13+
Node parent;
14+
Node left;
15+
Node right;
16+
17+
public Node(int data) {
18+
this.data = data;
19+
this.parent = null;
20+
this.left = null;
21+
this.right = null;
22+
}
23+
24+
@Override
25+
public String toString() {
26+
return "[" + data + "] --> ";
27+
}
28+
}
29+
30+
public static Node sortedArrayToBalancedBST(int[] sortedArr, int low, int high) {
31+
if (low > high) {
32+
return null;
33+
}
34+
35+
int mid = (low + high) / 2;
36+
37+
Node node = new Node(sortedArr[mid]);
38+
System.out.print(sortedArr[mid] + " --> ");
39+
node.left = sortedArrayToBalancedBST(sortedArr, low, mid - 1);
40+
node.right = sortedArrayToBalancedBST(sortedArr, mid + 1, high);
41+
42+
return node;
43+
}
44+
45+
public static void main(String[] args) {
46+
int[] sortedArr = {11, 22, 33, 44, 55, 66, 77, 88};
47+
sortedArrayToBalancedBST(sortedArr, 0, sortedArr.length - 1);
48+
}
49+
}

0 commit comments

Comments
 (0)