-
Notifications
You must be signed in to change notification settings - Fork 0
/
1382-Balance-a-Binary-Search-Tree.java
50 lines (44 loc) · 1.28 KB
/
1382-Balance-a-Binary-Search-Tree.java
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
42
43
44
45
46
47
48
49
50
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
public TreeNode balanceBST(TreeNode root) {
List<Integer> inorder = new ArrayList<>();
inOrderTrav(root, inorder);
return createBalanceBST(inorder, 0, inorder.size() - 1);
}
private void inOrderTrav(TreeNode root, List<Integer> inorder) {
if(root == null) return;
inOrderTrav(root.left, inorder);
inorder.add(root.val);
inOrderTrav(root.right, inorder);
}
private TreeNode createBalanceBST(
List<Integer> inorder,
int start,
int end
) {
if(start > end) return null;
int mid = start + (end - start) / 2;
TreeNode leftSubtree = createBalanceBST(inorder, start, mid-1);
TreeNode rightSubtree = createBalanceBST(inorder, mid+1, end);
TreeNode node = new TreeNode(
inorder.get(mid),
leftSubtree,
rightSubtree
);
return node;
}
}