● 669. 修剪二叉搜索树
● 108.将有序数组转换为二叉搜索树
● 538.把二叉搜索树转换为累加树
669. 修剪BST
自己写的居然过了,再看看随想录,居然和自己写的是一个思路,
看来确实进步了鸭
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return root;
if(root->val < low) {
return trimBST(root->right, low, high);
} else 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;
}
};
108. 将有序数组转换为二叉搜索树
简单
左闭右开
class Solution {
TreeNode* dfs(vector<int>& nums, int l, int r) {
if(l >= r) {
return nullptr;
}
int mid = (l + r) >> 1;
TreeNode* root = new TreeNode(nums[mid]);
root->left = dfs(nums, l, mid);
root->right = dfs(nums, mid + 1, r);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = dfs(nums, 0, nums.size());
return root;
}
};
538. 把二叉搜索树转换为累加树
emmm,转化成数组后发现是从右往左加(升序数组)
是中序遍历之后反向求和。
也就是右中左遍历
犯了个傻 写了个 pre += root->val ...
class Solution {
int pre = 0;
void Tarversal(TreeNode* root) {
if(root == nullptr) return;
Tarversal(root->right);
root->val += pre;
pre = root->val;
Tarversal(root->left);
}
public:
TreeNode* convertBST(TreeNode* root) {
Tarversal(root);
return root;
}
};