#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int value;
struct node *left;
struct node *right;
} Node;
Node *
newNode(int n){
Node *obj;
obj
= (Node
*)malloc(sizeof(Node
)); obj->value = n;
obj->left = NULL;
obj->right = NULL;
return obj;
}
Node *
addNode(Node *obj, int n){
if(obj == NULL){
return newNode(n);
}
if(obj->value == n){
/*do nothing*/
}else if(obj->value < n){
obj->right = addNode(obj->right, n);
} else{
obj->left = addNode(obj->left, n);/* (6) */
}
return obj;
}
Node *
appendRightEnd(Node *obj, Node *right){
if(obj != NULL){
if(obj->right == NULL){
obj->right = right;
}else{
obj->right = appendRightEnd(obj->right, right);/* (7) */;
}
}
return obj;
}
Node *
deleteNode(Node *obj, int n){
Node *newobj;
if(obj != NULL){
if(obj->value == n){
if (obj->left == NULL){
newobj = obj->right;
return newobj;
}else if(obj->right == NULL){
newobj = obj->left;/* (8) */
return newobj;
}else{
obj->left = appendRightEnd(obj->left, obj->right);
newobj = obj->left;
return newobj;
}
}else{
if(obj->value < n)
obj->right = deleteNode(obj->right, n);
else
obj->left = deleteNode(obj->left, n);/* (9) */
}
}
return obj;
}
void
printNodes(Node *obj){
if(obj != NULL){
if(obj->left != NULL){
printNodes(obj->left);
}
if(obj->right != NULL){
printNodes(obj->right);
}
}
}
int
main(int argc, char *argv[]){
Node *topnode = NULL;
topnode = addNode(topnode, 5);
topnode = addNode(topnode, 7);
topnode = addNode(topnode, 1);
topnode = addNode(topnode, -1);
topnode = addNode(topnode, 4);
topnode = addNode(topnode, 10);
printNodes(topnode);
topnode = deleteNode(topnode, 5);
printNodes(topnode);
}
I2luY2x1ZGU8c3RkaW8uaD4KI2luY2x1ZGU8c3RkbGliLmg+Cgp0eXBlZGVmIHN0cnVjdCBub2RlIHsKICBpbnQgdmFsdWU7CiAgc3RydWN0IG5vZGUgKmxlZnQ7CiAgc3RydWN0IG5vZGUgKnJpZ2h0Owp9IE5vZGU7CgpOb2RlICoKbmV3Tm9kZShpbnQgbil7CiAgTm9kZSAq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