验证二叉搜索树
#include <bits/stdc++.h>
using namespace std;
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:
bool isValidBST(TreeNode *root, TreeNode *Min, TreeNode *Max)
{
if (root == nullptr)
{
return true;
}
if (Min != nullptr && root->val <= Min->val)
{
return false;
}
if (Max != nullptr && root->val >= Max->val)
{
return false;
}
return isValidBST(root->left, Min, root) && isValidBST(root->right, root, Max);
}
bool isValidBST(TreeNode *root)
{
return isValidBST(root, nullptr, nullptr);
}
};
二叉搜索树中的搜索
#include <bits/stdc++.h>
using namespace std;
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 *searchBST(TreeNode *root, int val)
{
if (root == nullptr)
return nullptr;
if (root->val == val)
return root;
if (root->val > val)
{
return searchBST(root->left, val);
}
if (root->val < val)
{
return searchBST(root->right, val);
}
return nullptr;
}
};
二叉搜索树中的插入操作
#include <bits/stdc++.h>
using namespace std;
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 *insertIntoBST(TreeNode *root, int val)
{
if (root == NULL)
{
return new TreeNode(val);
}
if (root->val > val)
{
root->left = insertIntoBST(root->left, val);
}
else if (root->val < val)
{
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
删除二叉搜索树的节点
#include <bits/stdc++.h>
using namespace std;
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 *deleteNode(TreeNode *root, int key)
{
if (root == nullptr)
{
return nullptr;
}
if (root->val == key)
{
if (root->left == nullptr)
{
return root->right;
}
if (root->right == nullptr)
{
return root->left;
}
TreeNode *node = root->right;
while (node->left != nullptr)
{
node = node->left;
}
root->right = deleteNode(root->right, node->val);
node->left = root->left;
node->right = root->right;
root = node;
}
if (root->val > key)
{
root->left = deleteNode(root->left, key);
}
if (root->val < key)
{
root->right = deleteNode(root->right, key);
}
return root;
}
};