代码随想录算法训练营第20天| 669. 修剪二叉搜索树 ,108.将有序数组转换为二叉搜索树,538.把二叉搜索树转换为累加树
669. 修剪二叉搜索树
文章链接:https://programmercarl.com/0669.修剪二叉搜索树.html
题目链接:https://leetcode.cn/problems/trim-a-binary-search-tree/description/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==NULL) return NULL;
if(root->val<low){ //如果小于规定范围
TreeNode* node=trimBST(root->right,low,high);
return node;
}
else if(root->val>high){
TreeNode* node=trimBST(root->left,low,high);
return node;
}
else{
root->left=trimBST(root->left,low,high);
root->right=trimBST(root->right,low,high);
return root;
}
}
};
108.将有序数组转换为二叉搜索树
文章链接:https://programmercarl.com/0108.将有序数组转换为二叉搜索树.html
题目链接:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/description/
class Solution {
public:
TreeNode* traversal(vector<int>& nums,int left,int right){
if(left>right) return NULL;
int divIndex=left+(right-left)/2;
TreeNode* node=new TreeNode(nums[divIndex]);
node->left=traversal(nums,left,divIndex-1);
node->right=traversal(nums,divIndex+1,right);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return traversal(nums,0,nums.size()-1);
}
};
538.把二叉搜索树转换为累加树
文章链接:https://programmercarl.com/0538.把二叉搜索树转换为累加树.html
题目链接:https://leetcode.cn/problems/convert-bst-to-greater-tree/description/
class Solution {
public:
int sum=0;
void traversal(TreeNode* root){
//使用右中左的顺序
if(root==NULL) return;
traversal(root->right);
sum+=root->val;
root->val=sum;
traversal(root->left);
}
TreeNode* convertBST(TreeNode* root) {
traversal(root);
return root;
}
};