-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBalanceABinarySearchTree.java
More file actions
41 lines (38 loc) · 1.04 KB
/
Copy pathBalanceABinarySearchTree.java
File metadata and controls
41 lines (38 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
public class BalanceABinarySearchTree {
public TreeNode balanceBST(TreeNode root) {
List<Integer> arr=new ArrayList<>();
populateArray(root,arr);
return balance(0,arr.size()-1,arr);
}
public static TreeNode balance(int l,int h,List<Integer> arr){
if(l>h){
return null;
}
int mid=(l+h)/2;
TreeNode root=new TreeNode(arr.get(mid));
root.left=balance(l,mid-1,arr);
root.right=balance(mid+1,h,arr);
return root;
}
public void populateArray(TreeNode root,List<Integer> arr){
if(root==null){
return;
}
populateArray(root.left,arr);
arr.add(root.val);
populateArray(root.right,arr);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}