代码随想录day20 669. 修剪二叉搜索树 、108.将有序数组转换为二叉搜索树 、538.把二叉搜索树转换为累加树
669. 修剪二叉搜索树
我自己的思路是和前一道题一样,遇见一个不符合的就调用一次删掉该结点的函数,这样明显就麻烦了,其实只要小于左边界或大于右边界,就可以直接不要左子树或右子树,不必一个个比对
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {if (root == nullptr) {return nullptr;}TreeNode *left = trimBST(root->left,low,high);TreeNode *right = trimBST(root->right,low,high);if (root->val < low) {return right;}if (root->val > high) {return left;}root->left = left;root->right = right;return root;
}
};
108.将有序数组转换为二叉搜索树
秒了
class Solution {
public:TreeNode* traversal(vector<int>& nums,int left,int right) {if (left > right) {return nullptr;}int mid = left + ((right - left) >> 1);TreeNode *root = new TreeNode(nums[mid]);root->left = traversal(nums, left, mid - 1);root->right = traversal(nums, mid + 1, right);return root;}TreeNode* sortedArrayToBST(vector<int>& nums) {return traversal(nums, 0, nums.size() - 1);}
};
538.把二叉搜索树转换为累加树
不难,可以独自写出
class Solution {
public:int sum = 0;void traversal(TreeNode* root) {if (root == nullptr) {return;}traversal(root->right);sum += root->val;root->val = sum;traversal(root->left);}TreeNode* convertBST(TreeNode* root) {traversal(root);return root;}
};