- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1382.java
34 lines (30 loc) · 1.04 KB
/
_1382.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
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.ArrayList;
importjava.util.List;
publicclass_1382 {
publicstaticclassSolution1 {
publicTreeNodebalanceBST(TreeNoderoot) {
List<Integer> inorder = inorder(root, newArrayList<>());
returndfs(inorder, 0, inorder.size() - 1);
}
privateList<Integer> inorder(TreeNoderoot, List<Integer> list) {
if (root == null) {
returnlist;
}
inorder(root.left, list);
list.add(root.val);
returninorder(root.right, list);
}
privateTreeNodedfs(List<Integer> nums, intstart, intend) {
if (end < start) {
returnnull;
}
intmid = (start + end) / 2;
TreeNoderoot = newTreeNode(nums.get(mid));
root.left = dfs(nums, start, mid - 1);
root.right = dfs(nums, mid + 1, end);
returnroot;
}
}
}