class node { public: node *left; int info; node *right; };Note: To see how to define a tree node in Fortran 90, see the two sample programs at the end of Notes: Fortran-90 Pointers.
The gentree differs slightly from that found in The Essentials of Data Structures to avoid the global variable in C++ (a style highly discourage).
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //* F U N C T I O N G E N T R E E * // This generates a tree. n is a small positive integer // specifying an upper bound on the depth // of the tree. The nodes can have two children, and // an information field. The information field is //* given a sequential node number. * //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * node *gentree(int n, int & numnode) { node *t; t = new node; t->info = ++numnode; //numnode is the unique number //stored in each node after its creation if (n<=0) t->left = NULL; else t->left = gentree(n-1,numnode); if (n<=0) t->right = NULL; else t->right = gentree(n-1,numnode); return(t); }The following code prints a tree in inorder traversal.
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * //* P R O C E D U R E I N P R I N T * //* The information fields of the nodes of a tree // are printed in inorder traversal order. * //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * void inprint(node *t) { if (t!=NULL) { inprint(t->left); cout << t->info << endl; inprint(t->right); } }The main program code:
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //* main program //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * int main () { node *root; int numnode; // (* initialization *) numnode = 0; root = gentree(4,numnode); inprint(root); return 0; }A slightly different version of a running program can be found at this link.
This page is maintained by Dennis C. Smolarski, S.J.
© Copyright 1998, 1999 Dennis C. Smolarski, SJ, All rights reserved.
Last changed: 7 April 1999.