代码随想录算法训练营第22天 [235. 二叉搜索树的最近公共祖先 701.二叉搜索树中的插入操作 450.删除二叉搜索树中的节点 ]
一、235. 二叉搜索树的最近公共祖先
链接: 代码随想录.
思路:利用二叉搜索树的特性,公共祖先肯定在区间[p,q]
做题状态:看解析后做出来了
class Solution
{
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
return traversal(root, p, q);
}
TreeNode *traversal(TreeNode *cur, TreeNode *p, TreeNode *q)
{
if (cur == nullptr)
{
return nullptr;
}
// if (cur->val <= p->val && cur->val >= q->val)
// {
// return cur;
// }
//说明在节点右边
if (cur->val < p->val && cur->val < q->val)
{
TreeNode *right = traversal(cur->right, p, q);
if (right)
return right;
}
//说明在节点左边
if (cur->val > p->val && cur->val > q->val)
{
TreeNode *left = traversal(cur->left, p, q);
if (left)
return left;
}
return cur;
}
};
二、701.二叉搜索树中的插入操作
链接: 代码随想录.
思路:插入只需要找到符合条件的叶子节点直接插入就好了
做题状态:看解析后做出来了
// 递归
class Solution
{
public:
TreeNode *insertIntoBST(TreeNode *root, int val)
{
if (root == nullptr)
{
TreeNode *node = new TreeNode(val);
return node;
}
return travalsel(root, val);
}
TreeNode *travalsel(TreeNode *cur, int val)
{
if (cur == nullptr)
{
TreeNode *node = new TreeNode(val);
return node;
}
if (cur->val > val)
{
cur->left = travalsel(cur->left, val);
}
else
{
cur->right = travalsel(cur->right, val);
}
return cur;
}
};
//迭代法
class Solution
{
public:
TreeNode *insertIntoBST(TreeNode *root, int val)
{
if (root == nullptr)
{
TreeNode *node = new TreeNode(val);
return node;
}
TreeNode *cur = root;
TreeNode *parent = root;
while (cur != nullptr)
{
parent = cur;
if (cur->val < val)
{
cur = cur->right;
}
else if (cur->val > val)
{
cur = cur->left;
}
}
TreeNode *result = new TreeNode(val);
if (parent->val > val)
{
parent->left = result;
}
else
{
parent->right = result;
}
return root;
}
};
三、450.删除二叉搜索树中的节点
链接: 代码随想录.
思路: 五种情况
1.一直遍历下去都没找到相等的,说明树中没有要删除的节点,return nullptr
如果找到删除节点后
2.节点左子树右子树都为空,直接删除 return nullptr
3.节点左子树不为空,右子树为空,那就把左子树直接接上来, return root->left
4.节点右子树不为空,左子树为空,那就把右子树直接接上来, return root->right
5.节点左右子树都不为空,两种处理方式
(1) 把节点左子树 全部放到 节点右子树 的 最左下的节点 下 此时return root->right
(2) 把节点右子树 全部放到 节点左子树 的 最右下的节点 下 此时return root->left
6.需要接住之前return 的节点
如果key比当前节点大,说明要向右 返回的节点也接在root->right上
如果key比当前节点小,说明要向左 返回的节点也接在root->left上
做题状态:看解析后做出来了
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 && root->right != nullptr)
{
TreeNode *tmp = root->right;
delete root;
return tmp;
}
else if (root->left != nullptr && root->right == nullptr)
{
TreeNode *tmp = root->left;
delete root;
return tmp;
}
else if (root->left != nullptr && root->right != nullptr)
{
TreeNode *cur = root->right;
while (cur->left)
{
cur = cur->left;
}
cur->left = root->left;
TreeNode *tmp = root->right;
delete root;
return tmp;
}
}
if (key > root->val)
{
root->right = deleteNode(root->right, key);
}
else
{
root->left = deleteNode(root->left, key);
}
return root;
}
};