/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> v;
void inorder(TreeNode *root) {
if (!root) return;
inorder(root->left);
v.emplace_back(root);
inorder(root->right);
}
TreeNode *process(TreeNode *root, int left, int right) {
if (left > right) return nullptr;
int idx = (left + right) / 2;
root = v[idx];
root->left = process(root->left, left, idx - 1);
root->right = process(root->right, idx + 1, right);
return root;
}
TreeNode *balanceBST(TreeNode *root) {
inorder(root);
return process(nullptr, 0, v.size() - 1);
}
};
1382. 将二叉搜索树变平衡
最新推荐文章于 2023-06-21 12:50:48 发布