669. 修剪二叉搜索树
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) return root;
if (root->val > high) {
return trimBST(root->left, low, high);
}
else if (root->val < low) {
return trimBST(root->right, low, high);
}
else {
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
}
};
108. 将有序数组转换为二叉搜索树
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.empty()) return nullptr;
int length = nums.size();
int cur = length / 2;
if (length == 1) {
TreeNode* root = new TreeNode(nums[0]);
return root;
}
else if (length == 2) {
TreeNode* root = new TreeNode(nums[0]);
TreeNode* cur = new TreeNode(nums[1]);
root->right = cur;
return root;
}
else {
vector<int> numsLeft(nums.begin(), nums.begin() + cur);
vector<int> numsRight(nums.begin() + cur + 1, nums.end());
TreeNode* root = new TreeNode(nums[cur]);
root->left = sortedArrayToBST(numsLeft);
root->right = sortedArrayToBST(numsRight);
return root;
}
}
};
538. 把二叉搜索树转换为累加树
class Solution {
public:
int pre = 0;
void backtracking(TreeNode* root) {
if (root == nullptr) return;
backtracking(root->right);
root->val += pre;
pre = root->val;
backtracking(root->left);
}
TreeNode* convertBST(TreeNode* root) {
if (root == nullptr) return root;
backtracking(root);
return root;
}
};