538把二叉搜索树转化为累加树
class Solution {
public:
TreeNode* convertBST(TreeNode* root)
{
dg(root);
return root;
}
int sum=0;
void dg(TreeNode*root)
{
if(root==nullptr) return ;
dg(root->right);
sum+=root->val;
root->val=sum;
dg(root->left);
}
};
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;
}
};
108 将有序数组转化为二叉树
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
TreeNode* node= sort(nums,0,nums.size()-1);
return node;
}
TreeNode*sort (vector<int>&nums,int l,int r)
{
if(l>r) return nullptr;
int m=(l+r)/2;
TreeNode*node= new TreeNode(nums[m]);
node->left=sort(nums,l,m-1);
node->right=sort(nums,m+1,r);
return node;
}
};