235. 二叉搜索树的最近公共祖先
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
根据二叉搜索树的定义,最近的公共祖先一定是遍历到[p.val, q.val]之间的数(假设p比q小)。如果当前节点比pq节点都大,那就往左继续遍历;如果当前节点比pq节点都小,那就往右遍历
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return nullptr;
TreeNode* answer = root;
while(true) {
if(answer->val < p->val && answer->val < q->val) {
answer = answer->right;
continue;
}
else if(answer->val > p->val && answer->val > q->val) {
answer = answer->left;
continue;
}
else break;
}
return answer;
}
};
701.二叉搜索树中的插入操作
https://leetcode.cn/problems/insert-into-a-binary-search-tree/
这个没什么好说的,一路往下遍历找到应该插入的位置即可
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root) return new TreeNode(val);
TreeNode* cur = root;
while(true) {
if(val < cur->val) {
if(!cur->left) {
cur->left = new TreeNode(val);
break;
}
cur = cur->left;
}
else {
if(!cur->right){
cur->right = new TreeNode(val);
break;
}
cur = cur->right;
}
}
return root;
}
};
450.删除二叉搜索树中的节点
https://leetcode.cn/problems/delete-node-in-a-bst/
想要删除二叉搜索树的节点,情况比较复杂
情况1:该节点没有左右孩子,直接删除即可
情况2:该节点有左右孩子中的一个,删除该节点,将该节点的左右孩子移到该节点的位置
情况3:该节点左右孩子都存在,删除该节点,让左孩子移动到该节点的位置,让右节点成为左节点的右孩子;若左节点本身存在右孩子,那就让右孩子成为左节点右孩子的右孩子,以此类推,直到将右节点重新加入二叉树中为止。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return nullptr;
if(root->val == key) {
if(!root->left && !root->right) {
delete root;
return nullptr;
}
if(root->left && !root->right) {
TreeNode* cur = root->left;
delete root;
return cur;
}
if(!root->left && root->right) {
TreeNode* cur = root->right;
delete root;
return cur;
}
if(root->left && root->right) {
TreeNode* cur = root->left;
while(cur->right) cur = cur->right;
cur->right = root->right;
cur = root->left;
delete root;
return cur;
}
}
root->left = deleteNode(root->left, key);
root->right = deleteNode(root->right, key);
return root;
}
};