文章目录
Leetcode 235-二叉搜索树的最近公共祖先
题目描述
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
解题思路
利用二叉搜索树的特性,p 和 q 的最近公共祖先的值应该介于两者值之间
递归法:
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);
}
else if (root->val < p->val && root->val < q->val) {
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};
迭代法:
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 nullptr;
}
};
注意在循环之外需要 return nullptr 处理当 root 为空的情况。
Leetcode 701-二叉搜索树中的插入操作
题目描述
https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
解题思路
在叶子节点插入待插入节点:
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);
}
else if (root->val < val) {
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
Leetcode 450-删除二叉搜索树中的节点
题目描述
https://leetcode.cn/problems/delete-node-in-a-bst/description/
解题思路
在删除过程中有五种情况:
- 二叉树中不存在要删除的节点;
- 要删除的节点是叶子节点;
- 要删除的节点子节点左不空右空;
- 要删除的节点子节点左空右不空;
- 要删除的节点子节点左不空右不空
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)return nullptr;
else if (root->left == nullptr && root->right != nullptr)return root->right;
else if (root->left != nullptr && root->right == nullptr)return root->left;
else {
TreeNode* cur = root->right;
while (cur->left != nullptr) {
cur = cur->left;
}
cur->left = root->left;
return root->right;
}
}
if (root->val > key) root->left=deleteNode(root->left, key);
else if (root->val < key) root->right = deleteNode(root->right, key);
return root;
}
};