669. 修剪二叉搜索树
class Solution {
public:
TreeNode* traversal(TreeNode* root, int low, int high){
TreeNode* left, *right;
if (root==nullptr) return nullptr;
if (root->val < low){
left = traversal(root->right, low, high);
return left; //如果当前节点小于low,就直接返回该节点右子树中符合条件的节点替代,当前节点。由当前节点的父节点的左子树接住此left。*
}
if (root->val > low){
right = traversal(root->right, low, high);
return right;
}
root->left = left; //在这里接住*
root->right = right;
return root;
}
TreeNode* trimBST(TreeNode* root, int low, int high) {
return traversal(root, low, high);
}
};
#108.将有序数组转换为二叉搜索树
class Solution {
public:
TreeNode* insert(int left, int right, vector<int>& nums){
int middle = (left+right)/2;
if (left > right) return nullptr;
TreeNode* node = new TreeNode(nums[middle]);
node->left = insert(left, middle-1, nums);
node->right = insert(middle+1, right, nums);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return insert(0, nums.size()-1, nums);
}
};
538.把二叉搜索树转换为累加树
class Solution {
public:
int sum=0;
void sumTree(TreeNode* root){
if (root == nullptr) return ;
if (root->right != nullptr) {
sumTree(root->right);
}
//中的处理
sum+=root->val;
root->val = sum;
//
if (root->left != nullptr) {
sumTree(root->left);
}
}
TreeNode* convertBST(TreeNode* root) {
sumTree(root);
return root;
}
};