修剪二叉树
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;
}
把二叉树转换为累加树
int sum = 0;
void bst(TreeNode* root){
if(!root)
return;
bst(root->right);
sum += root->val;
root->val = sum;
bst(root->left);
return;
}
TreeNode* convertBST(TreeNode* root) {
bst(root);
return root;
}
将有序数组转换为平衡二叉树
TreeNode* bst(vector<int> &nums, int left, int right){
if(left > right){
return nullptr;
}
int mid = (left + right)/2;
//添加根节点
TreeNode* root = new TreeNode(nums[mid]);
root->left = bst(nums, left, mid - 1);
root->right = bst(nums, mid + 1, right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return bst(nums, 0, nums.size()-1);
}