669. 修剪二叉搜索树
思路与重点
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) 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 L, int R) {
if (!root) return nullptr;
while (root != nullptr && (root->val < L || root->val > R)) {
if (root->val < L) root = root->right;
else root = root->left;
}
TreeNode *cur = root;
while (cur != nullptr) {
while (cur->left && cur->left->val < L) {
cur->left = cur->left->right;
}
cur = cur->left;
}
cur = root;
while (cur != nullptr) {
while (cur->right && cur->right->val > R) {
cur->right = cur->right->left;
}
cur = cur->right;
}
return root;
}
};
108.将有序数组转换为二叉搜索树
思路与重点
- 首先取数组中间元素的位置,不难写出int mid = (left + right) / 2;,这么写其实有一个问题,就是数值越界,例如left和right都是最大int,这么操作就越界了,在二分法中尤其需要注意!
class Solution {
public:
TreeNode* BST(vector<int>& nums, int L, int R){
if(L > R) return nullptr;
int rootIdx = L + ((R - L) / 2);
TreeNode* root = new TreeNode(nums[rootIdx]);
root->left = BST(nums, L, rootIdx - 1);
root->right = BST(nums, rootIdx + 1, R);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return BST(nums, 0, nums.size() - 1);
}
};
- 迭代解法:迭代法可以通过三个队列来模拟,一个队列放遍历的节点,一个队列放左区间下标,一个队列放右区间下标,模拟的就是不断分割的过程。
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.size() == 0) return nullptr;
TreeNode* root = new TreeNode(0);
queue<TreeNode*> nodeQue;
queue<int> leftQue;
queue<int> rightQue;
nodeQue.push(root);
leftQue.push(0);
rightQue.push(nums.size() - 1);
while (!nodeQue.empty()) {
TreeNode* curNode = nodeQue.front();
nodeQue.pop();
int left = leftQue.front(); leftQue.pop();
int right = rightQue.front(); rightQue.pop();
int mid = left + ((right - left) / 2);
curNode->val = nums[mid];
if (left <= mid - 1) {
curNode->left = new TreeNode(0);
nodeQue.push(curNode->left);
leftQue.push(left);
rightQue.push(mid - 1);
}
if (right >= mid + 1) {
curNode->right = new TreeNode(0);
nodeQue.push(curNode->right);
leftQue.push(mid + 1);
rightQue.push(right);
}
}
return root;
}
};
538.把二叉搜索树转换为累加树
思路与重点
class Solution {
public:
int addval = 0;
TreeNode* convertBST(TreeNode* root) {
if(root == nullptr) return nullptr;
convertBST(root->right);
root->val += addval;
addval = root->val;
convertBST(root->left);
return root;
}
};
二叉树总结