今日任务
235. 二叉搜索树的最近公共祖先
- 题目链接: https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
- 题目描述:

Code
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q){
return root;
}
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if(left && right){
return root;
}
if(left){
return left;
}
return right;
}
};
701.二叉搜索树中的插入操作
- 题目链接: https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
- 题目描述:

Code
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr){
return new TreeNode(val);
}
if(val < root->val){
root->left = insertIntoBST(root->left, val);
}else{
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
450.删除二叉搜索树中的节点
- 题目链接: https://leetcode.cn/problems/delete-node-in-a-bst/description/
- 题目描述:

Code
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr){
return nullptr;
}
if(key < root->val){
root->left = deleteNode(root->left, key);
}else if(key > root->val){
root->right = deleteNode(root->right, key);
}else{
auto cur = root;
if(root->left == nullptr){
cur = cur->right;
delete root;
return cur;
}
if(root->right == nullptr){
cur = cur->left;
delete root;
return cur;
}
cur = cur->left;
while(cur->right){
cur = cur->right;
}
cur->right = root->right;
auto rst = root->left;
delete root;
return rst;
}
return root;
}
};