Cod sursa(job #2193598)

Utilizator Horia14Horia Banciu Horia14 Data 10 aprilie 2018 17:41:30
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
// Binary Search Tree
#include<cstdio>
using namespace std;

struct node {
    int key;
    node* left, *right;
};

node* root;

struct node* newNode(int x) {
    node* elem = new node;
    elem->key = x;
    elem->left = elem->right = NULL;
    return elem;
};

struct node* insertBST(struct node* node, int key) {
    if(node == NULL)
        return newNode(key);
    if(key < node->key)
        node->left = insertBST(node->left,key);
    else
        node->right = insertBST(node->right,key);
    return node;
};

struct node* searchBST(struct node* node, int key) {
    if(node == NULL || node->key == key)
        return node;
    if(key < node->key)
        return searchBST(node->left,key);
    return searchBST(node->right,key);
};

struct node* minValue(struct node* node) {
    struct node* tmp = node;
    while(tmp->left != NULL)
        tmp = tmp->left;
    return tmp;
};

struct node* deleteNode(struct node* root, int key) {
    if(root == NULL)
        return root;
    if(key < root->key)
        root->left = deleteNode(root->left,key);
    else if(key > root->key)
        root->right = deleteNode(root->right,key);
    else {
        if(root->left == NULL) {
            struct node* tmp = root->right;
            delete root;
            return tmp;
        } else if(root->right == NULL) {
            struct node* tmp = root->left;
            delete root;
            return tmp;
        }
        struct node* tmp = minValue(root->right);
        root->key = tmp->key;
        root->right = deleteNode(root->right,tmp->key);
    }
    return root;
};

int main() {
    int n, op, x, i;
    FILE* fin, *fout;
    fin = fopen("hashuri.in","r");
    fout = fopen("hashuri.out","w");
    fscanf(fin,"%d",&n);
    root = NULL;
    for(i = 1; i <= n; i++) {
        fscanf(fin,"%d%d",&op,&x);
        if(op == 1) {
            if(searchBST(root,x) == NULL)
                root = insertBST(root,x);
        } else if(op == 2)
            root = deleteNode(root,x);
        else {
            if(searchBST(root,x) != NULL)
                fprintf(fout,"1\n");
            else fprintf(fout,"0\n");
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}