Day 21 21天养成一个好习惯
一、思路
过不了啊啊啊啊啊啊啊 2h 滚
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==nullptr) return nullptr;
if(root->val>high || root->val<low){
if(root->left==nullptr&&root->right==nullptr){
root=nullptr;
return root;
}
else if(root->left==nullptr){
root=root->right;
if(root->val>high || root->val<low){
root=trimBST(root,low,high);
}
return root;
// auto retNode = root->right;
// delete root;
// return retNode;
}
else if(root->right==nullptr){
root=root->left;
if(root->val>high || root->val<low){
root=trimBST(root,low,high);
}
return root;
// auto retNode = root->left;
// delete root;
// return retNode;
}
else{
if(root->val>high){
root=root->left;
return root;
}
else{
root=root->right;
return root;
}
if(root->val>high || root->val<low){
root=trimBST(root,low,high);
}
}
}
if(root)root->left=trimBST(root->left,low,high);
if(root)root->right=trimBST(root->right,low,high);
return root;
}
};
二、代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr ) return nullptr;
if (root->val < low) {
TreeNode* right = trimBST(root->right, low, high); // 寻找符合区间[low, high]的节点
return right;
}
if (root->val > high) {
TreeNode* left = trimBST(root->left, low, high); // 寻找符合区间[low, high]的节点
return left;
}
root->left = trimBST(root->left, low, high); // root->left接入符合条件的左孩子
root->right = trimBST(root->right, low, high); // root->right接入符合条件的右孩子
return root;
}
};
108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
TreeNode* traversal(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 = traversal(nums, left, mid - 1);
root->right = traversal(nums, mid + 1, right);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = traversal(nums, 0, nums.size() - 1);
return root;
}
};
538. 把二叉搜索树转换为累加树 - 力扣(LeetCode)
class Solution {
private:
int pre = 0; // 记录前一个节点的数值
void traversal(TreeNode* cur) { // 右中左遍历
if (cur == NULL) return;
traversal(cur->right);
cur->val += pre;
pre = cur->val;
traversal(cur->left);
}
public:
TreeNode* convertBST(TreeNode* root) {
pre = 0;
traversal(root);
return root;
}
};