summaryrefslogblamecommitdiff
path: root/btree-int.c
blob: 3622ffba36363e48892fcada3ce88a6e2d7cc1c9 (plain) (tree)
1
2
3
4
5
6
7
8
9


                   
             


                       
  
 



                                      
 
                         
                       
 





                              


                                         














                                    

 
                         







                                       

 
                         







                         

 
                                 
                           
 









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

struct node {
	long v;
	struct node *l;
	struct node *r;
};

struct node *cn(long);
void an(struct node *, struct node *);
void pn(struct node *);
void fn(struct node *);

struct node *cn(long v) {
	struct node *n;

	n = malloc(sizeof *n);
	if (!n)
		return NULL;
	n->v = v;
	n->l = n->r = NULL;
	return n;
}

void an(struct node *r, struct node *n) {
	if (!r || !n)
		return;
	if (n->v > r->v) {
		if (r->r)
			an(r->r, n);
		else
			r->r = n;
	}
	else {
		if (r->l)
			an(r->l, n);
		else
			r->l = n;
	}
	return;
}

void pn(struct node *n) {
	if (!n)
		return;
	if (n->l)
		pn(n->l);
	fprintf(stdout, "%ld\n", n->v);
	if (n->r)
		pn(n->r);
	return;
}

void fn(struct node *n) {
	if (!n)
		return;
	if (n->l)
		fn(n->l);
	if (n->r)
		fn(n->r);
	free(n);
	return;
}

int main(int argc, char **argv) {
	struct node *r, *n;

	r = NULL;
	for (argv++; *argv; argv++) {
		n = cn(atoi(*argv));
		if (!n)
			break;
		if (r)
			an(r, n);
		else
			r = n;
	}

	pn(r);

	fn(r);

	exit(EXIT_SUCCESS);
}