669. 修剪二叉搜索树 - 力扣(LeetCode)
思路:当前结点大于有右边界时直接返回它的左子树,小于左边界时返回当前结点的右子树
重点:使用左右结点接受返回的结点覆盖结点,删除需要删除的结点
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);
}
if(root->val<low){
return trimBST(root->right,low,high);;
}
root->left=trimBST(root->left,low,high);
root->right=trimBST(root->right,low,high);
return root;
}
};
108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
思路:二分法建树,左闭右闭区间
重点:平衡二叉搜索树
class Solution {
public:
TreeNode* fun(vector<int>& nums,int left,int right){
if(left>right){
return nullptr;
}
int mid=left+(right-left)/2;
TreeNode* root=new TreeNode(nums[mid]);
root->left=fun(nums,left,mid-1);
root->right=fun(nums,mid+1,right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return fun(nums,0,nums.size()-1);;
}
};
538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
思路:累加树是中序遍历后,从后向前累加,结点的值为后缀和,使用一个额外变量存放累加和,进行反中序遍历时进行赋值
重点:反中序遍历,全局变量存储累加和
class Solution {
public:
int pre=0;
TreeNode* convertBST(TreeNode* root) {
if(root==nullptr){
return nullptr;
}
convertBST(root->right);
pre+=root->val;
root->val=pre;
convertBST(root->left);
return root;
}
};
总结
建树和修改树,可以考虑使用左右子树接受递归的值,达到删除和修改的要求