文档讲解:代码随想录 (programmercarl.com)
视频讲解:代码随想录的个人空间-代码随想录个人主页-哔哩哔哩视频 (bilibili.com)
LeetCode 修剪二叉搜索树
题目链接:669. 修剪二叉搜索树 - 力扣(LeetCode)
解题思路:递归没写出来,确实理解不是很到位。目前觉得,递归写法就是按照正常逻辑去写即可,类似伪代码那种写个递归的大纲,之后分析写出来的代码哪里有漏洞,捋一遍思路。迭代法写在下面,用于练手。
代码如下:
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(!root)return nullptr;
if(root->val<low)return trimBST(root->right,low,high);
if(root->val>high)return trimBST(root->left,low,high);
root->left=trimBST(root->left,low,high);
root->right=trimBST(root->right,low,high);
return root;
}
};
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
while(root&&(root->val<low||root->val>high)){
if(root->val<low)root=root->right;
else root=root->left;
}
TreeNode* cur=root;
while(cur){
while(cur->left&&cur->left->val<low){
cur->left=cur->left->right;
}
cur=cur->left;
}
cur=root;
while(cur){
while(cur->right&&cur->right->val>high){
cur->right=cur->right->left;
}
cur=cur->right;
}
delete cur;
return root;
}
};
LeetCode 将有序数组转换为二叉搜索树
题目链接:108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
解题代码如下:
class Solution {
public:
TreeNode* traversal(vector<int>& nums,int low,int high){
if(low>high)return nullptr;
int mid=low+(high-low)/2;
TreeNode* node=new TreeNode(nums[mid]);
node->left=traversal(nums,low,mid-1);
node->right=traversal(nums,mid+1,high);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return traversal(nums,0,nums.size()-1);
}
};
LeetCode 把二叉搜索树转换为累加树
题目链接:538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
解题思路:右中左累加遍历即可。
解题代码如下:
class Solution {
public:
int num=0;
TreeNode* convertBST(TreeNode* root) {
if(!root)return nullptr;
root->right=convertBST(root->right);
root->val+=num;
num=root->val;
root->left=convertBST(root->left);
return root;
}
};