Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

n-ary tree

Status
Not open for further replies.

tokool

Programmer
Nov 6, 2001
40
US
Hi,
I am looking for code snippets that implement a n-ary tree.
I wold appriciate if i could get some sites where i could find the code.
Thanks,
Preetham.
 
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>



#define MAXWORD 100

#define getch() getc(fpin)
#define ungetch(x) ungetc(x,fpin)




FILE *fpin;


struct tnode{
	char *word;
	int count;
	struct tnode *left;
	struct tnode *right;
};



struct tnode *addtree(struct tnode *, char *);
void treeprint(struct tnode *);
int getword(char *,int);
struct tnode *talloc(void);



int main(){

	struct tnode *root;
	char word[MAXWORD];

	fpin=fopen(&quot;c:\\file3.txt&quot;,&quot;r&quot;);

	root=NULL;

	while(getword(word,MAXWORD) != EOF)
		if( isalpha(word[0]) )
			root = addtree(root,word);

	treeprint(root);

	fclose(fpin);
	return 0;

}


struct tnode *addtree(struct tnode *p, char *w){

	int cond;

	if(p == NULL){

		p = talloc();
		p->word = strdup(w);
		p->count = 1;
		p->left = p->right = NULL;

	}else if( ( cond = strcmp(w,p->word) ) == 0)
		p->count++;

	else if(cond < 0){
		p->left = addtree(p->left,w);

	}else{
		p->right = addtree(p->right,w);

	}
	return p;


}



int getword(char *word, int lim){

	int c;
	char *w = word;

	while( isspace( c = getch() ) )
		;

	if (c != EOF)
		*w++ = c;

	if(!isalpha(c)){

		*w = '\0';
		return c;
	}

	for(;--lim > 0; w++)
		if( !isalnum( *w = getch() ) ){
			ungetch(*w);
			break;
		}

	*w = '\0';
	return word[0];

}


void treeprint(struct tnode *p){

	if ( p != NULL){

		treeprint(p->left);
		printf(&quot;%4d %s\n&quot;, p->count, p->word);
		treeprint(p->right);
	}

}


struct tnode *talloc(){

	return (struct tnode *) malloc( sizeof(struct tnode) );

}

bluenote@clorinda.dnsq.org
(excuse my english)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top