/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* trimBST(struct TreeNode* root, int low, int high){
if (root == NULL) {
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;
}
}
思路:这道题删除二叉树中的树值很类似,但是我们不能直接将它的子结点返回,而是要对它的子结点进行修剪后才可以返回
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* traversal(int* nums, int left, int right){
if (left > right)
return NULL;
int mid = left + ((right - left) / 2);
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[mid];
root->left = traversal(nums, left, mid-1);
root->right = traversal(nums, mid+1, right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
struct TreeNode* root = traversal(nums, 0, numsSize - 1);
return root;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int pre = 0;
void travseal(struct TreeNode* root)
{
if(!root)
return ;
travseal(root->right);
root->val = root->val + pre;
pre = root->val;
travseal(root->left);
}
struct TreeNode* convertBST(struct TreeNode* root) {
pre = 0;
travseal(root);
return root;
}