Hi,
This is my first ever attempt at writing a recursive function in c. The following-code works. I apologize for the long posting, but I am trying to be as clear as possible.
I am trying to generate a tree where each node (inode) has an integer field "n". Correspondingly, each inode has an array of pointers to "n" other inodes. Function inode *I = gen_tree(inode *I, int nlevels);
generates a tree with random number of inodes at each level. The tree is generated in a depth-first fashion. I have several questions.
(a) Is there a better way to write the function?? Any feedback/suggestions would be appreciated.
(b) Can the tree be generated in a BF fashon?
(c) I->i
should have an index in which the tree is traversed. How can I write a function to compute I->i
?
(d) I->c
should have cumulative-sum of all inodes below a given node. How can I write a function to compute I->c
?
Thanks in advance,
~Russ
//.h file:
typedef struct integerNode {
int n;
int c;
int i;
struct integerNode **nodes;
} inode;
inode *new_inode( int n );
inode *gen_itree( inode *I, int nlevels );
//Constructor:
inode *new_inode( int n ){
inode *I;
I = malloc( sizeof (inode ) );
I->n = n;
I->nodes = malloc( n * sizeof (inode* ) );
return (I );
};
//Generating tree with random-number of nodes:
inode *gen_itree( inode *I, int nlevels ){
int i, next_level, next_n;
printf( " \n" );
printf( " I : %p\n", I );
printf( " ***** nlevels : %d\n", nlevels );
printf( " *************\n" );
if ( nlevels == 0 ) {
printf( " nlevels == 0!\n");
} else {
printf( " I->n : %d\n", I->n );
printf( " *************\n" );
next_level = nlevels - 1;
for ( i = 0; i < I->n; i++ ) {
printf( " I: %p\n",I);
printf( " adding node number: %d\n", i );
next_n = 0 + rand( ) % 3;
I->nodes[i] = new_inode( next_n );
printf( " I->nodes[%d]->n: %p, %d\n",i, I->nodes[i],next_n);
I->nodes[i] = gen_itree( I->nodes[i], next_level );
}
}
printf( " *************\n" );
printf( " returning I : %p\n", I );//This part is unclear to me!
printf( " *************\n" );
return (I);
}
//Main.c
int main( int argc, char** argv ){
inode *I;
I = new_inode( 2 );
I = gen_itree(I,3);
return ( 1 );
}