1.修剪二叉搜索数
1.1 题目
. - 力扣(LeetCode)
1.2 题解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high)
{
//递归终止条件
if (root == nullptr)return nullptr;
//如果当前遍历的节点值小于low
if (root->val < low)
{
//则去遍历它的右节点
TreeNode* tmp=trimBST(root->right, low, high);
return tmp;
}
//如果当前遍历的节点值大于high
if (root->val > high)
{
//则去遍历它的左节点
TreeNode* tmp = trimBST(root->left, low, high);
return tmp;
}
//左
root->left=trimBST(root->left, low, high);
//右
root->right=trimBST(root->right, low, high);
return root;
}
};
2.将有序数组转换为二叉树
2.1 题目
. - 力扣(LeetCode)
2.2 题解
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
return Traversal(nums, 0, nums.size() - 1);
}
TreeNode* Traversal(vector<int>& nums, int left, int right)
{
//确定终止条件
if (left > right)return nullptr;
//确定单层递归逻辑
int middle = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[middle]);
root->left = Traversal(nums, left, middle - 1);
root->right = Traversal(nums, middle + 1, right);
return root;
}
};
3.把二叉搜索树转换为累加树
3.1 题目
. - 力扣(LeetCode)
3.2 题解
class Solution {
public:
int pre = 0;
TreeNode* convertBST(TreeNode* root)
{
Traversal(root);
return root;
}
void Traversal(TreeNode* node)
{
if (node == nullptr)return;
//右
Traversal(node->right);
//中
node->val += pre;
pre = node->val;
//左
Traversal(node->left);
}
};