235. 二叉搜索树的最近公共祖先
和昨天的一题很像,两种做法
1、dfs
class Solution {
public:
// dfs版
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left == nullptr && right == nullptr) return nullptr;
if (left == nullptr) return right;
if (right == nullptr) return left;
return root;
}
};
2、利用二叉搜索树的特性
class Solution {
public:
// 不需要dfs,普通遍历即可
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr || root == p || root == q) return root;
if (p->val > q->val) swap(p, q);
while (root != nullptr)
{
if (root->val < q->val && root->val > p->val)
return root;
if (root->val == p->val || root->val == q->val)
return root;
if (root->val > p->val)
root = root->left;
else
root = root->right;
}
return nullptr;
}
};
701. 二叉搜索树中的插入操作
找到的点,一定有位置,直接插入即可。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == nullptr) return new TreeNode(val);
TreeNode* work = root;
TreeNode* pre = root;
while (work != nullptr)
{
pre = work;
if (work->val < val) work = work->right;
else if (work->val > val) work = work->left;
}
TreeNode* res = new TreeNode(val);
if (val < pre->val)
pre->left = res;
else pre->right = res;
return root;
}
};
450. 删除二叉搜索树中的节点
五种情况:没搜到;叶子节点;左空;右空;都不为空
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == nullptr) return nullptr;
if (key > root->val) root->right = deleteNode(root->right, key); // 去右子树
else if (key < root->val) root->left = deleteNode(root->left, key); // 去左子树
else
{
if (!root->left) return root->right; // 待删除的节点没有左孩子,直接把右孩子返回给上一级
if (!root->right) return root->left; // 没有右孩子
// 找到右孩子的左下
TreeNode* node = root->right;
while (node->left)
node = node->left;
node->left = root->left;
root = root->right;
}
return root;
}
};