#include #include #include "tree_ops.h" node * newNode( tree * t ) { node * n = malloc(sizeof(node)); n->tree = t; n->next = 0; return n; } list * newList( ) { list *lp = malloc(sizeof(list)); lp->nb = 0; lp->first = lp->last = 0; return lp; } void addANode( list * lp, node * np ) { if( lp->nb++ == 0 ) lp->first = np; else lp->last->next = np; lp->last = np; } void printList( list *lp ) { node *np = lp->first; while( np != 0 ) { fprintf(stderr,"%s ",np->tree->name); np = np->next; } } // Create a tree; may successively add children to it later, using addAChild() tree * newTree( char * name ) { tree * tp = malloc(sizeof(tree)); tp->name = name; tp->children = newList(); return tp; } void printTreeName( tree *tp ) { fprintf(stderr,"%s ",tp->name ); } void addAChild( tree *t, tree *child ) { addANode( t->children, newNode(child) ); } // Create a "leaf tree" (when knowing there will be no child) tree * newLeaf( char * name ) { tree * tp = malloc(sizeof(tree)); tp->name = name; tp->children = 0; return tp; } // Create a tree, with a ready-made list of children tree * newTreeWithGivenChildren( char * name, list *children ) { tree * tp = malloc(sizeof(tree)); tp->name = name; tp->children = children; return tp; } void DFSPrintTree( tree * t, FILE * fp ) { list * children = t->children; node * currNode; fprintf(fp,"%s ",t->name ); if( children && children->nb ) { fprintf(fp,"("); currNode = children->first; while( currNode ) { DFSPrintTree( currNode->tree, fp ); currNode = currNode->next; } fprintf(fp,")"); } } void DFSVisitor( tree * t, void (*f)( ), int level ) { list * children = t->children; node * currNode; (*f)( t->name, level ); if( children && children->nb ) { currNode = children->first; while( currNode ) { DFSVisitor( currNode->tree, f, level+1 ); currNode = currNode->next; } } }