#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
} Node;

Node* create_node(int key) {
    Node* n = (Node*)malloc(sizeof(Node));
    n->data = key;
    n->left = n->right = NULL;
    return n;
}

// 이 위로 수정 금지

#define Visitnode(n) printf("%d ", (n)->data)
#define KEY(n) ((n)->data)

Node* insert_bst(Node* root, int A){
    if(root == NULL){
        return create_node(A);
    }

    if(A < KEY(root)){
        root->left = insert_bst(root->left, A);
    }
    else if(A > KEY(root)){
        root->right = insert_bst(root->right, A);
    }
    
    return root;
}

Node* delete_bst(Node* root, int key){
    if(root == NULL){
        return NULL;
    }

    if(KEY(root) > key){
        root->left = delete_bst(root->left, key);
    }
    else if(KEY(root) < key){
        root->right = delete_bst(root->right, key);
    }
    else{
        Node* n = root;

        if(root->left == NULL){
            root = root->right;
            free(n);
        }
        else if(root->right == NULL){
            root = root->left;
            free(n);
        }
        else{
            Node* succ= root->right;

            while(succ->left != NULL){
                succ = succ->left;
            }

            root->data = succ->data;
            root->right = delete_bst(root->right,succ->data);
        }
    }
    return root;
}

void preorder(Node* A){
    if(A != NULL){
        Visitnode(A);
        preorder(A->left);
        preorder(A->right);
    }
}


// 이 아래로 수정 금지
int main() {
    int N;
    scanf("%d", &N);

    Node* root = NULL;

    for (int i = 0; i < N; i++) {
        int x;
        scanf("%d", &x);
        root = insert_bst(root, x);
    }

    if (root != NULL)
        root = delete_bst(root, root->data);

    preorder(root);
    printf("\n");

    return 0;
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: