501. 二叉搜索树中的众数
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/247de51075b72da04e2d5fde6b6592e2.png)
class Solution {
public:
void search_bst(TreeNode* cur, unordered_map<int, int>& mp)
{
if (cur == nullptr) return;
mp[cur->val]++;
search_bst(cur->left, mp);
search_bst(cur->right, mp);
}
public:
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> mp;
vector<int> res;
if (root == nullptr) return res;
search_bst(root, mp);
vector<pair<int, int>> vec(mp.begin(), mp.end());
sort(vec.begin(), vec.end(),
[](const pair<int, int>& x, const pair<int, int>& y) -> bool
{
return x.second > y.second;
});
res.push_back(vec[0].first);
for (int i = 1; i < vec.size(); i++)
{
if (vec[i].second == vec[0].second) res.push_back(vec[i].first);
else break;
}
return res;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/754964756ec32430367466891349cf3a.png)
701. 二叉搜索树中的插入操作
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3c2186a49da4b81a4667d320554413d4.png)
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == nullptr)
{
TreeNode* node = new TreeNode(val);
return node;
}
if (root->val > val) root->left = insertIntoBST(root->left, val);
if (root->val < val) root->right = insertIntoBST(root->right, val);
return root;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/eda0797924b6e08e8818892b22d2ad07.png)
450.删除二叉搜索树中的节点
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7b53485ee60b1b22f39684a784fc3de4.png)
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) return root;
if (root->val == key)
{
if (root->left == nullptr && root->right == nullptr)
{
delete root;
return nullptr;
}
else if (root->left == nullptr)
{
TreeNode* retNode = root->right;
delete root;
return retNode;
}
else if (root->right == nullptr)
{
TreeNode* retNode = root->left;
delete root;
return retNode;
}
else
{
TreeNode* cur = root->right;
while (cur->left != nullptr)
{
cur = cur->left;
}
cur->left = root->left;
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
}
if (root->val > key) root->left = deleteNode(root->left, key);
if (root->val < key) root->right = deleteNode(root->right, key);
return root;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c9cf156edca684588545ebeb184c6cbb.png)
669. 修剪二叉搜索树
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ad644fff134ecdf0cfa4042cab94dce6.png)
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) return nullptr;
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;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7b2c319577678da476d6179a2725faa3.png)