目录
LeeCode 235.二叉搜索树的最近公共祖先
LeeCode 701.二叉搜索树中的插入操作
LeeCode 450.删除二叉搜索树中的节点
LeeCode 235.二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
思路:在BST中,若中间节点是 p 和 q 的公共祖先,那么中节点的数组一定在[p,q] 区间内,即中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是q 和 p的公共祖先。
递归法:
class Solution {
private:
TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur == NULL) return cur;
if (cur->val > p->val && cur->val > q->val) {
TreeNode* left = traversal(cur->left, p ,q);
if (left != NULL) return left;
}
if (cur->val < p->val && cur->val < q->val) {
TreeNode* right = traversal(cur->right, p, q);
if (right != NULL) return right;
}
return cur;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return traversal(root, p, q);
}
};
迭代法:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root) {
if (root->val > p->val && root->val > q->val) root = root->left;
else if(root->val < p->val && root->val < q->val) root = root->right;
else return root;
}
return NULL;
}
};
LeeCode 701.二叉搜索树中的插入操作
701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
思路:遍历二叉搜索树,找到空节点插入元素。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == NULL) {
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;
}
};
LeeCode 450.删除二叉搜索树中的节点
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
思路:
删除节点的可能情况:
1.未找到删除的节点,遍历到空节点后返回;
2.找到删除的节点,为叶子节点,直接删除;
3.找到删除的节点,左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点;
4.找到删除的节点,左孩子不为空,右孩子为空,删除节点,左孩子补位,返回左孩子为根节点;
5.找到删除的节点,左右孩子都不为空,将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == NULL) return root;
if (root->val == key) {
if (root->left == NULL && root->right == NULL) {
delete root;
return NULL;
}
else if (root->left == NULL) {
auto retNode = root->right;
delete root;
return retNode;
}
else if (root->right == NULL) {
auto retNode = root->left;
delete root;
return retNode;
}
else {
TreeNode* cur = root->right;
while(cur->left != NULL) cur= cur->left;
cur->left = root->left;
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
}
if (root->val > key) root->left = deleteNode(root->left, key);
if (root->val < key) root->right = deleteNode(root->right, key);
return root;
}
};