day21 二叉树8
669. 修剪二叉搜索树
递归法:
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) {
return root;
}
if (root->val < low) {
TreeNode* right = trimBST(root->right, low, high);
return right;
}
if (root->val > high) {
TreeNode* left = trimBST(root->left, low, high);
return left;
}
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) {
if (root == nullptr) {
return root;
}
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;
}
return root;
}
};
108.将有序数组转换为二叉搜索树
class Solution {
public:
TreeNode* toBst(vector<int> &nums, int left, int right) {
if (left >= right) {
return nullptr;
}
int mid = left + (right - left) / 2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = toBst(nums, left, mid);
node->right = toBst(nums, mid + 1, right);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return toBst(nums, 0, nums.size());
}
};
迭代法太麻烦了,不写了
538.把二叉搜索树转换为累加树
class Solution {
public:
int sumNum = 0;
void getSum(TreeNode* root) {
if (root == nullptr) {
return;
}
sumNum += root->val;
getSum(root->left);
getSum(root->right);
}
TreeNode* convert(TreeNode* root) {
if (root == nullptr) {
return root;
}
root->left = convert(root->left);
sumNum -= root->val;
root->val += sumNum;
root->right = convert(root->right);
return root;
}
TreeNode* convertBST(TreeNode* root) {
getSum(root);
return convert(root);
}
};
二叉搜索树的左中右是从小到大的,右中左就是从大到小的,反着写更方便,不用求和了。
class Solution {
public:
int sumNum = 0;
TreeNode* convertBST(TreeNode* root) {
if (root == nullptr) {
return root;
}
root->right = convertBST(root->right);
sumNum += root->val;
root->val = sumNum;
root->left = convertBST(root->left);
return root;
}
};