forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1382.cpp
More file actions
27 lines (24 loc) · 659 Bytes
/
1382.cpp
File metadata and controls
27 lines (24 loc) · 659 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
class Solution {
public:
TreeNode* balanceBST(TreeNode* root) {
inOrder(root);
return sortedToBST(0, res.size() - 1);
}
private:
vector<int> res;
void inOrder(TreeNode* root) {
if (root != nullptr) {
inOrder(root->left);
res.emplace_back(root->val);
inOrder(root->right);
}
}
TreeNode* sortedToBST(int l, int r) {
if (l > r) return nullptr;
int mid = (l + r) >> 1;
TreeNode* root = new TreeNode(res[mid]);
root->left = sortedToBST(l, mid - 1);
root->right = sortedToBST(mid + 1, r);
return root;
}
};