1、LeetCode669修剪二叉搜索树
题目链接:669、修剪二叉搜索树
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == NULL) return root;
if (root->val < low)
{
TreeNode* right = trimBST(root->right, low, high);
return right;
}
if (root->val > high)
{
TreeNode* left = trimBST(root->left, low, high);
return left;
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
2、LeetCode108 将有序数组转换为二叉搜索树
题目链接:108、将有序数组转换为二叉搜索树
class Solution {
public:
TreeNode* traversal(vector<int>& nums, int left, int right)
{
if (left >= right) return nullptr;
int mid = left + ((right - left) / 2);
TreeNode* root = new TreeNode(nums[mid]);
root->left = traversal(nums, left, mid);
root->right = traversal(nums, mid+1, right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return traversal(nums, 0, nums.size());
}
};
3、LeetCode538把二叉搜索树转换为累加树
题目链接:538、把二叉搜索树转换为累加树
本题右中左遍历,双指针。
class Solution {
public:
int pre = 0;
void traversal(TreeNode* root)
{
if (root == NULL) return;
traversal(root->right);
root->val += pre;
pre = root->val;
traversal(root->left);
}
TreeNode* convertBST(TreeNode* root) {
traversal(root);
return root;
}
};