forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1382.java
More file actions
25 lines (22 loc) · 672 Bytes
/
1382.java
File metadata and controls
25 lines (22 loc) · 672 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
class Solution {
public TreeNode balanceBST(TreeNode root) {
inOrder(root);
return sortedToBST(0, res.size() - 1);
}
private List<Integer> res = new ArrayList();
private void inOrder(TreeNode root) {
if (root != null) {
inOrder(root.left);
res.add(root.val);
inOrder(root.right);
}
}
private TreeNode sortedToBST(int l, int r) {
if (l > r) return null;
int mid = (l + r) >> 1;
TreeNode root = new TreeNode(res.get(mid));
root.left = sortedToBST(l, mid - 1);
root.right = sortedToBST(mid + 1, r);
return root;
}
}