-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancingBST.java
More file actions
29 lines (23 loc) · 804 Bytes
/
BalancingBST.java
File metadata and controls
29 lines (23 loc) · 804 Bytes
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
//1382. Balance a Binary Search Tree
import java.util.*;
class Solution {
List<Integer> inorder = new ArrayList<>();
public TreeNode balanceBST(TreeNode root) {
inorderTraversal(root);
return buildBalancedBST(0, inorder.size() - 1);
}
private void inorderTraversal(TreeNode root) {
if (root == null) return;
inorderTraversal(root.left);
inorder.add(root.val);
inorderTraversal(root.right);
}
private TreeNode buildBalancedBST(int left, int right) {
if (left > right) return null;
int mid = left + (right - left) / 2;
TreeNode root = new TreeNode(inorder.get(mid));
root.left = buildBalancedBST(left, mid - 1);
root.right = buildBalancedBST(mid + 1, right);
return root;
}
}