Attention:
When constructing a two-fork tree, use a double pointer and a return value when using a single heavy pointer.
The code is as follows:
/* The input space here represents NULL, by default the input data parameters are automatically assigned when the function is executed, and no storage space is consumed until the function is executed, so we use a double pointer to construct the tree. Thus, we pass in a pointer to the pointer of the tree node, so that when the function is executed, even if the pointer is released, the data of the tree node that we save by *t can be called by the pointer t of the tree nodes. Conversely, if we pass in a pointer to a tree node, when the function is finished, the pointer is destroyed, and the Createbitree () function returns no value, so it is equal to the function not being called. */#include <stdio.h> #include <stdlib.h>typedef char elemtype;typedef struct bitnode{elemtype data; struct Bitnode *lchild; struct Bitnode *rchild;} bitnode,*bitree;typedef struct Bitnode *linktree;void createbitree (Bitree *t) {char C; scanf ("%c", &c); if (' = = = c) {(*t) = NULL; } else {(*t) = (linktree) malloc (sizeof (Bitnode)); (*t)->data = c; Createbitree (& (*t)->lchild); Createbitree (& (*t)->rchild); }}void Preordertraverse (Bitree t,int level) {if (T) {printf ("%c->", t->data); Preordertraverse (t->lchild,level+1); Preordertraverse (t->rchild,level+1); }}void Inordertraverse (Bitree t,int level) {if(T) {inordertraverse (t->lchild,level+1); printf ("%c->", t->data); Inordertraverse (t->rchild,level+1); }}void Postordertraverse (Bitree t,int level) {if (T) {postordertraverse (t->lchild,level+1); Postordertraverse (t->rchild,level+1); printf ("%c->", t->data); }}int Main () {int level = 1; Bitree T = NULL; Createbitree (&t); printf ("The result of a pre-order traversal is: \ n"); Preordertraverse (T,level); printf ("\ n" The result of a pre-order traversal: \ n "); Inordertraverse (t,level+1); printf ("\ n" The result of a pre-order traversal: \ n "); Postordertraverse (T,level); return 0;}
The construction and traversal of binary tree (pre-order, middle order, post sequence)