235. 二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
class Solution {
public:
// 当出现第一个在[min, max]的值时,这个值一定是最近公共祖先,因为p,q一定会出现在左右数
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr){
return root;
}
if(root->val > p->val && root->val > q->val) // 此时节点在p,q右边
{
TreeNode* left = lowestCommonAncestor(root->left, p, q);
if(left != nullptr){
return left;
}
}
if(root->val < p->val && root->val < q->val){
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(right != nullptr){
return right;
}
}
return root;
}
};
701.二叉搜索树中的插入操作
701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr){
TreeNode* newNode = new TreeNode(val);
return newNode;
}
if(root->val < val){
root->right = insertIntoBST(root->right, val);
}
if(root->val > val){
root->left = insertIntoBST(root->left, val);
}
return root;
}
};
450.删除二叉搜索树中的节点
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr){
return root;
}
if(root->val == key){
if(root->left == nullptr){
return root->right;
}
if(root->right == nullptr){
return root->left;
}
TreeNode* rightLeftNode = root->right;
while(rightLeftNode->left != nullptr){
rightLeftNode = rightLeftNode->left;
}
rightLeftNode->left = root->left;
return root->right;
}
if(root->val > key){
root->left = deleteNode(root->left, key);
}
if(root->val < key){
root->right = deleteNode(root->right, key);
}
return root;
}
};
382

被折叠的 条评论
为什么被折叠?



