235 二叉搜索树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
int v1=min(p->val,q->val);
int v2=max(p->val,q->val);
return find(root,v1,v2);
}
TreeNode* find(TreeNode* root, int v1, int v2)
{
if(root==nullptr) return nullptr;
if(root->val>v2)
{
return find(root->left,v1,v2);
}
if(root->val<v1)
{
return find(root->right,v1,v2);
}
return root;
}
};
701 二叉搜索树的插入
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val)
{
if(root==nullptr)
{
return new TreeNode(val);
}
if(root->val<val)
{
root->right=insertIntoBST(root->right,val);
}
if(root->val>val)
{
root->left=insertIntoBST(root->left,val);
}
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) {
return nullptr;
}
else if(!root->left) return root->right;
else if(!root->right) return root->left;
else{
TreeNode* mint=getmin(root->right);
root->right=deleteNode(root->right,mint->val);
mint->left=root->left;
mint->right=root->right;
root=mint;
}
}
else if(root->val>key)
{
root->left=deleteNode(root->left,key);
}
else if(root->val<key){
root->right=deleteNode(root->right,key);
}
return root;
}
TreeNode*getmin(TreeNode*root)
{
while(root->left!=NULL)
{
root=root->left;
}
return root;
}
};