Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Shitty program

Name: Anonymous 2010-05-24 23:11

Hi /prog/. I'm learning C, and wrote a program that takes a bunch of numbers and sorts them using a binary tree. I know it's not an efficient way to sort, I'm just learning binary trees. Could you look over it real quick and just give me some comments, like if there was something you would have done differently or something that's just stupid. Thanks a lot.

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

struct node_ {
        int value;
        struct node_ *left, *right;
};

typedef struct node_ node;

node *insert(node *parent, int newval)
{
        if (!parent) {
                node *n = malloc(sizeof(node));
                n->value = newval;
                return n;
        }
        else if (newval == parent->value)
                return parent;
        else if (newval < parent->value) {
                parent->left = insert(parent->left, newval);
                return parent;
        }
        else {
                parent->right = insert(parent->right, newval);
                return parent;
        }
}

void print(node *top)
{
        if (!top)
                return;

        print(top->left);
        printf("%d ", top->value);
        print(top->right);
}

int main(int argc, char *argv[])
{
        puts("enter values, 0 to stop");
       
        int next;
        scanf("%d", &next);
       
        node *root = 0;
       
        while (next) {
                root = insert(root, next);
                scanf("%d", &next);
        }

        print(root);
        puts("");

        return 0;
}

Name: Anonymous 2010-05-25 23:01

Here's version 2, did I fix everything mentioned? I did change the behavior to keep duplicate values. Also, I added some basic malloc checking, but I'm not worried about scanf for this.

Also thanks, you have all been really helpful.

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

typedef struct node {
    int value;
    struct node *left, *right;
} node;

node *insert(node *parent, int newval)
{
    if (!parent) {
        node *n = malloc(sizeof(node));

        if (!n) {
            puts("malloc failed");
            return 0;  
        }      

        n->value = newval;
        n->left = n->right = 0;
        return n;
    }  

    if (newval <= parent->value)
        parent->left = insert(parent->left, newval);
    else
        parent->right = insert(parent->right, newval);

    return parent;
}

void print(node *top)
{
    if (!top)
        return;

    print(top->left);
    printf("%d ", top->value);
    print(top->right);
}

int main(int argc, char *argv[])
{
    puts("enter values, 0 to stop");

    int next;
    scanf("%d", &next);

    node *root = 0;

    while (next) {
        root = insert(root, next);
        scanf("%d", &next);
    }  

    print(root);
    puts("");

    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List