669. 修剪二叉搜索树
struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
if (!root)
return NULL;
//修剪:三种情况
if (root->val < low)
return trimBST(root->right, low, high);
else if (root->val > high)
return trimBST(root->left, low, high);
else{
root->left = trimBST(root->left, low, high);
//连接修剪好的左子树
root->right = trimBST(root->right, low, high);
return root;
}
}
108.将有序数组转换为二叉搜索树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* create_AVL(int *nums,int left,int right){
if(left>right) return NULL;//终止条件
//处理当前结点
int mid=(left+right)/2;
struct TreeNode* node=(struct TreeNode*)calloc(1,sizeof(struct TreeNode));
node->val=nums[mid];
//左闭右开
//递归处理并连接左右子树
node->left=create_AVL(nums,left,mid-1);
node->right=create_AVL(nums,mid+1,right);
return node;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
return create_AVL(nums,0,numsSize-1);
}
538.把二叉搜索树转换为累加树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//倒序遍历(从最大的开始遍历):右中左
void change_BST(struct TreeNode* root, int* pre) {
if (!root)
return;
change_BST(root->right, pre);
root->val += (*pre);
*pre = root->val;
change_BST(root->left, pre);
}
struct TreeNode* convertBST(struct TreeNode* root) {
int pre = 0;
change_BST(root, &pre);
//pre是全局性的→用指针
return root;
}