修剪二叉搜索树
力扣题目链接
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(!root)
return nullptr;
if(root->val >= low && root->val <= high){
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
}
else if(root->val < low){
return trimBST(root->right, low, high);
}
else if(root->val > high){
return trimBST(root->left, low, high);
}
return root;
}
};
将有序数组转换为二叉搜索树
力扣题目链接
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBST(nums, 0, nums.size()-1);
}
TreeNode* sortedArrayToBST(vector<int>& nums, int stratIndex, int endIndex) {
if(stratIndex > endIndex)
return nullptr;
int mid = (stratIndex + endIndex)/2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = sortedArrayToBST(nums, stratIndex, mid-1);
node->right = sortedArrayToBST(nums, mid+1, endIndex);
return node;
}
};
把二叉搜索树转换为累加树
力扣题目链接
class Solution {
public:
int sum;
TreeNode* convertBST(TreeNode* root) {
sum = 0;
traversal(root);
return root;
}
void traversal(TreeNode* root){
if(!root)
return;
if(root->right)
traversal(root->right);
root->val += sum;
sum = root->val;
if(root->left)
traversal(root->left);
}
};