day16打卡
1.二叉搜索树的最近公共祖先
/**
- Definition for a binary tree node.
- struct TreeNode {
-
int val; -
TreeNode *left; -
TreeNode *right; -
TreeNode(int x) : val(x), left(NULL), right(NULL) {} - };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr)
{
return nullptr;
}
if(root->val > p->val && root->val > q->val)
{
return lowestCommonAncestor(root->left, p, q);
}
if(root->val < p->val && root->val < q->val)
{
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};
- 二叉搜索树中的插入操作
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;
}
};
- 删除二叉搜索树中的节点
/**
- 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 deleteNode(TreeNode* root, int key) {
if(root == nullptr)
{
return nullptr;
}
if(root->val == key)
{
if(root->left == nullptr && root->right == nullptr)
{
delete root;
return nullptr;
}
else if(root->left != nullptr && root->right == nullptr)
{
TreeNode *node = root->left;
delete root;
return node;
}
else if(root->left == nullptr && root->right != nullptr)
{
TreeNode *node = root->right;
delete root;
return node;
}
else
{
TreeNode *cur = root->right;
//TreeNode tmp = root;
while(cur->left != nullptr)
{
cur = cur->left;
}
cur->left = root->left;
// delete tmp;
// return cur;
TreeNode tmp = root; // 把root节点保存一下,下面来删除
root = root->right; // 返回旧root的右孩子作为新root
delete tmp; // 释放节点内存(这里不写也可以,但C++最好手动释放一下吧)
return root;
}
}
if(root->val > key)
{
root->left = deleteNode(root->left, key);
}
if(root->val < key)
{
root->right = deleteNode(root->right, key);
}
return root;
}
};

浙公网安备 33010602011771号