235 二叉搜索树的最近公共祖先
题目链接
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
思路
根据二叉搜索树的特性,两个节点的公共祖先,一定位于他们值的区间内。从顶向下遍历,碰到的第一个位于区间的值就是他们的最近公共祖先。因为此时这两个节点一定分别在左子树和右子树。再向下遍历,就会进入左子树或者右子树中,便会错过公共祖先。
文章详解
235. 二叉搜索树的最近公共祖先 | 二叉搜索树 | 最近公共祖先 | 有序性 | 代码随想录
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || !p || !q) {
return NULL;
}
if ((root->val > p->val && root->val < q->val) ||
(root->val < p->val && root->val > q->val)) {
return root;
}
if(root->val < p-> val && root->val < q->val)
{
return lowestCommonAncestor(root->right,p,q);
}
else if(root->val > p->val && root->val > q->val)
{
return lowestCommonAncestor(root->left,p,q);
}
return root; //恰好等于p或者q
}
};
701 二叉搜索树中的插入操作
题目链接
701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
思路
我们只需要遍历到二叉搜索树的空节点位置插入即可。(按照其规则)
文章详解
701.二叉搜索树中的插入操作 | 二叉搜索树 | 插入操作 | 递归迭代 | 代码随想录
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL)
{
TreeNode * newNode = new TreeNode(val);
return newNode;
}
if(root->val > val)
{
root->left = insertIntoBST(root->left,val);
}
else{
root->right = insertIntoBST(root->right,val);
}
return root;
}
};
450 二叉树:删除二叉搜索树中的节点
题目链接
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
思路
需要分五种情况:
- 目标值不存在
- 目标节点左子树和右子树都为空
- 目标节点左子树为空
- 目标节点右子树为空
- 都不为空。该情况下,需要将左子树移动到右子树的最左孩子之下。
文章详解
450.删除二叉搜索树中的节点 | 二叉搜索树 | 删除节点 | 结构调整 | 代码随想录
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL)
{
return NULL;
}
if(root->val == key)
{
if(root->left == NULL && root->right == NULL)
{
delete root;
return NULL;
}
if(root->left == NULL)
{
TreeNode* node = root->right;
delete root;
return node;
}
if(root->right == NULL)
{
TreeNode* node = root->left;
delete root;
return node;
}
//都不为空,将左子树移动到右子树的最左孩子之下
TreeNode * tmp = root->right;
while(tmp->left != NULL)
{
tmp = tmp->left;
}
tmp->left = root->left;
TreeNode *cur = root;
root = root->right;
delete cur;
return root;
}
if(root->val < key)
{
root->right = deleteNode(root->right,key);
}
else root->left = deleteNode(root->left,key);
return root;
}
};