day22打卡
235. 二叉搜索树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root->val > p->val && root->val > q->val)
{
TreeNode* left = lowestCommonAncestor(root->left, p, q);
return left;
}
else if(root->val < p->val && root->val < q->val)
{
TreeNode* right = lowestCommonAncestor(root->right, p, q);
return right;
}
else
return root;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root)
{
if(root->val > p->val && root->val > q->val)
{
root = root->left;
}
else if(root->val < p->val && root->val < q->val)
{
root = root->right;
}
else
return root;
}
return NULL;
}
};
701. 二叉搜索树中的插入操作
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
dfs(root, val);
return root;
}
TreeNode* dfs(TreeNode* root, int val)
{
if(root == nullptr)
{
root = new TreeNode(val);
return root;
}
if(root->val > val) root->left = dfs(root->left, val);
if(root->val < val) root->right = dfs(root->right, val);
return root;
}
};
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr)
{
root = new TreeNode(val);
return root;
}
TreeNode* cur = root;
TreeNode* pre = nullptr;
while(cur)
{
pre = cur;
if(cur->val > val) cur = cur->left;
else cur = cur->right;
}
if(val > pre->val) pre->right = new TreeNode(val);
else pre->left = new TreeNode(val);
return root;
}
};
450. 删除二叉搜索树中的节点
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) {
auto retNode = root->right;
delete root;
return retNode;
}
else if (root->right == nullptr) {
auto 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;
}
};
class Solution {
private:
TreeNode* deleteOneNode(TreeNode* target) {
if (target == nullptr) return target;
if (target->right == nullptr) return target->left;
TreeNode* cur = target->right;
while (cur->left) {
cur = cur->left;
}
cur->left = target->left;
return target->right;
}
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) return root;
TreeNode* cur = root;
TreeNode* pre = nullptr;
while (cur) {
if (cur->val == key) break;
pre = cur;
if (cur->val > key) cur = cur->left;
else cur = cur->right;
}
if (pre == nullptr) {
return deleteOneNode(cur);
}
if (pre->left && pre->left->val == key) {
pre->left = deleteOneNode(cur);
}
if (pre->right && pre->right->val == key) {
pre->right = deleteOneNode(cur);
}
return root;
}
};