235. 二叉搜索树的最近公共祖先
题目链接/文章讲解: 代码随想录
解题思路
p和q,如果都小于当前节点,那么就去左子树搜素,如果p和q都大于当前节点就去搜索右子树
如果p在左边,q在右边,那么他们相交的节点就是最近祖先,因为从上往下搜索,所以直接return
递归法
class Solution {
public:
TreeNode* travelSal(TreeNode* cur,TreeNode* p,TreeNode* q)
{
if(cur==NULL) return NULL; //终止条件
//左处理,pq值都小于当前节点,向左去搜
if(p->val < cur->val && q->val <cur->val)
{
TreeNode* left = travelSal(cur->left,p,q);
if(left != NULL) return left;
}
if(p->val > cur->val && q->val > cur->val)
{
TreeNode* right = travelSal(cur->right,p,q);
if(right!=NULL) return right;
}
return cur;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return travelSal(root,p,q);
}
};
迭代法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root)
{
if(p->val < root->val && q->val < root->val) root = root->left;
else if(p->val > root->val && q->val > root->val) root = root->right;
else return root;
}
return root;
}
};
对于二叉搜索树来说,迭代法一般比较简单,因为搜索树已经帮我们确定好了搜索顺序
701.二叉搜索树中的插入操作
题目链接/文章讲解: 代码随想录
解题思路
我们只需要始终往叶子节点去插入即可
递归法
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==nullptr)
{
TreeNode* node = new TreeNode(val);
return node; //一直想左递归,遇到空了,返回新建节点,在上一层去接
}
if(val< root->val) root->left = insertIntoBST(root->left,val);
if(val > root->val) root->right = insertIntoBST(root->right,val);
return root;
}
};
迭代法
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == NULL) {
TreeNode* node = new TreeNode(val);
return node;
}
TreeNode* cur = root;
TreeNode* parent = root; // 这个很重要,需要记录上一个节点,否则无法赋值新节点
while (cur != NULL) {
parent = cur;
if (cur->val > val) cur = cur->left;
else cur = cur->right;
}
TreeNode* node = new TreeNode(val);
if (val < parent->val) parent->left = node;// 此时是用parent节点的进行赋值
else parent->right = node;
return root;
}
};
450.删除二叉搜索树中的节点
题目链接/文章讲解:代码随想录
解题思路
一共有五个情况
没有找到删除节点 (直接返回)
叶子节点,左空右空 (直接删)
左不空,右空 (左孩子上位)
左空右不空 (右孩子上位)
左不空,右不空 (左右孩子都可以上位,选右孩子,就把左子树移到右孩子的最左侧节点的下面即可)
终止条件就是要找到要删的节点,随后去处理逻辑
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)
{
delete root;
return nullptr;
} //遇到叶子节点,直接返回null给上层节点接住
else if(root->left!=nullptr && root->right ==nullptr)
{
TreeNode* temp = root->left;
delete root;
return temp; //将自己的左孩子返回给自己的父节点
}
else if(root->left == nullptr && root->right !=nullptr)
{
TreeNode* temp = root->right;
delete root;
return temp; //将自己右孩子返回给自己的父节点
}
else
{
TreeNode* cur = root->right; //当前要删除节点的右孩子
while(cur->left!=nullptr)
cur = cur->left; //一直移动到左边
cur->left = root->left; //将要删除节点的左孩子,移动到右孩子的最左侧节点
TreeNode* node = root->right;
delete root;
return node;
}
}
if(key < root->val) root->left= deleteNode(root->left,key);
if(key > root->val) root->right = deleteNode(root->right,key); //将返回值接住
return root;
}
};
收获
继续加油