[C] Binary Search Tree 구현

숲사람·2022년 5월 4일
0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
        int val;
        char *name;
        struct node *left;
        struct node *right;
};

struct node *gen_node(int val, char *name)
{
        struct node *new = (struct node*)malloc(sizeof(struct node));
        new->val = val;
        new->name = name;
        new->left = NULL;
        new->right = NULL;
        return new;
}

/*
 * inseart new node in treep
 */
struct node *add_node(struct node *p_node, struct node *new_node)
{
        int cmp = 0;

        if (p_node == NULL)
                return new_node;

        cmp = strcmp(new_node->name, p_node->name);
        if (cmp == 0)
                ; // skip for same name
        else if(cmp < 0)
                p_node->left = add_node(p_node->left, new_node);
        else if(cmp > 0)
                p_node->right = add_node(p_node->right, new_node);
        return p_node;
}

/* 
 * search & returnthe node has "name"
 */
struct node *lookup(struct node *treep, char *name)
{
        int cmp;
        if (treep == NULL)
                return NULL;
        cmp = strcmp(name, treep->name);
        if (cmp == 0)
                return treep;
        else if (cmp < 0)
                return lookup(treep->left, name);
        else
                return lookup(treep->right, name);
}


int main(int argc, char *argv[])
{
        struct node *head = gen_node(0, "ccc");
        add_node(head, gen_node(1, "aaa"));
        add_node(head, gen_node(2, "fff"));
        add_node(head, gen_node(3, "bbb"));
        add_node(head, gen_node(20, "kk"));
        add_node(head, gen_node(87, "jihun"));
        add_node(head, gen_node(30, "kernel"));
        //printf("%s %s\n", head->name, head->left->name);
        printf("%d\n", lookup(head, "jihun")->val);
        printf("%d\n", lookup(head, "kernel")->val);
        return 0;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글