669. 修剪二叉搜索树
https://leetcode.cn/problems/trim-a-binary-search-tree/
修剪二叉搜索树容易出错的部分就是,当某节点小于最小范围时,它的右孩子可能在范围之内,但它右孩子的左孩子可能又不在范围内,所以要经历多重判断。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(!root) 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;
}
};
108.将有序数组转换为二叉搜索树
https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/
其实思路很简单,找到数组的中位创建根节点,然后以中位为分割线分割两个数组,这两个数组对应的就是根节点的左孩子和右孩子,不断重复这个过程就行。
直接分割数组:
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.empty()) return nullptr;
int mid = nums.size() / 2;
TreeNode* node = new TreeNode(nums[mid]);
vector<int> leftNums(nums.begin(), nums.begin() + mid);
vector<int> rightNums(nums.begin() + mid + 1, nums.end());
node->left = sortedArrayToBST(leftNums);
node->right = sortedArrayToBST(rightNums);
return node;
}
};
利用下标分割:
class Solution {
public:
TreeNode* traversal(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 = traversal(nums, left, mid);
node->right = traversal(nums, mid + 1, right);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return traversal(nums, 0, nums.size());
}
};
538.把二叉搜索树转换为累加树
https://leetcode.cn/problems/convert-bst-to-greater-tree/
这个简单,魔改一下中序遍历,让遍历顺序为右、中、左;然后在这基础上添加一个pos变量作为累积值,每一个节点添加先前已经记录的pos变量,然后更新pos变量的值即可。
class Solution {
public:
int pos = 0;
TreeNode* convertBST(TreeNode* root) {
if(!root) return nullptr;
convertBST(root->right);
root->val += pos;
pos = root->val;
convertBST(root->left);
return root;
}
};