struct Node{
Node* left;
int val;
Node* right;
};
Node* findLeftmostDelete(Node* t, int& x){
if(t->left == nullptr){
x = t->val;
Node* discard = t;
t = t->right;
delete discard;
return t;
}
t->left = findLeftMostDelete(t->left, x);
return t;
}
Node* deleteNodeItem(Node* t){
if((t->left == nullptr) && (t->right == nullptr)){
delete t;
t = nullptr;
}
else if(t->right == nullptr){
Node* discard = t;
t = t->left;
delete discard;
}
else if(t->left == nullptr){
Node* discard = t;
t = r->right;
delete discard;
}
else {
int x;
t->right = findLestmostDelete(t->right, x);
t->val = x;
}
return t;
}
Node* deleteItem(Node* t, int x, bool& found){
if(t == nullptr){
found == false;
return nullptr;
}
if(x == t->val){
found = true;
return deleteNodeItem(t);
}
if(x < t->val){
t->left = deleteItem(t->left, x, found);
}
else {
t->right = deleteItem(t->right, x, found);
}
return t;
}
Node* makeLeaf(int x){
Node* p = new Node;
p->left = nullptr;
p->val = x;
p->right = nullptr;
return p;
}
Node* insert(int x, Node* p){
if(p == nullptr)
return makeLeaf(x);
if(x < p->val)
p->left = insert(x, p->left);
else
p->right = insert(x, p->right);
return p;
}