›
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL){
TreeNode* node = new TreeNode(val);
return node;
}
if(root->val > val) root->left = insertIntoBST(root->left, val);
if(root->val < val) root->right = insertIntoBST(root->right, val);
return root;
}
};
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
//case1:没找到,则返回null
if(root == NULL) return root;
//case2:找到了
if(root->val == key){
//1)左右子树都为空
//2)左子树为空,右子树不为空
if(!root->left) return root->right;
//3)右子树为空,左子树不为空
else if(!root->right) return root->left;
else{ //4)左右子树都不为空
//寻找右子树的最左边结点,并把root->left放到该结点的左结点上,最后返回root->right
TreeNode* cur = root->right;
while(cur->left!= NULL){
cur = cur->left;
}
cur->left = root->left;
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
}
if(key < root->val){
root->left = deleteNode(root->left, key);
}
if(key > root->val){
root->right = deleteNode(root->right, key);
}
return root;
}
};
class Solution {
public:
//需要遍历整棵树
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return NULL;
if(root->val < low){
TreeNode* left = trimBST(root->right, low, high);
return left;
}
if(root->val > high){
TreeNode* right = trimBST(root->left, low, high);
return right;
}
//需要遍历整棵树,所以就不再上面前面加条件了,
//和删除和插入的不同之处
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
class Solution {
public:
TreeNode* convert(TreeNode* root, int &sum){
if(!root) return root;
root->right = convert(root->right, sum);
root->val = sum + root->val;
sum = root->val;
root->left = convert(root->left, sum);
return root;
}
TreeNode* convertBST(TreeNode* root) {
if(!root) return root;
int sum = 0;
return convert(root, sum);
}
};
class Solution {
public:
TreeNode* createSearch(vector<int>& nums, int start, int end){
//严格按照左闭又开的原则
if(start == end) return NULL;
int mid = (start + end) / 2;
TreeNode* root = new TreeNode(nums[mid]);
if(start + 1 == end) return root;
root->left = createSearch(nums, start, mid);
root->right = createSearch(nums, mid + 1, end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return createSearch(nums, 0, nums.size());
}
};