Binary Tree storage:
Sequential storage is a waste of space.
Binary Tree chain storage structure:
Typedef int datatype;
Typedef struct node {
Datatype data;
Struct node * lchild, * rchild;
} Bitree, * root;
Because of the recursive nature of Binary trees, the traversal algorithm is also recursive. The three basic Traversal Algorithms are as follows:
First, access the root of the tree, then access the left subtree, and then access the right subtree to traverse the root.
First access the left subtree, then access the root of the tree, and finally access the root traversal in the right subtree
First access the left subtree, then access the right subtree, and finally access the root traversal after the root of the root.
/******************** Binary Tree ***************** * *****/# include <stdio. h> # include <stdlib. h> # define n 16 typedef struct _ node _ {int no; struct _ node _ * lchild, * rchild;} bitree; typedef bitree * datatype; typedef struct {datatype data [N]; int front, rear;} sequeue; sequeue * createemptysequeue () {sequeue * sq; sq = (sequeue *) malloc (sizeof (sequeue); SQ-> front = SQ-> rear = 0; return sq;} int emptysequeue (sequeue * SQ) {return SQ-> front = SQ-> rear;} void ensequeue (sequeue * SQ, datatype X) {SQ-> rear = (SQ-> rear + 1) % N; SQ-> data [SQ-> rear] = x; return;} datatype desequeue (sequeue * sq) {SQ-> front = (SQ-> front + 1) % N; return SQ-> data [SQ-> front];} bitree * createbitree (int I, int N) {bitree * root; root = (bitree *) malloc (sizeof (bitree); root-> NO = I; If (2 * I <= N) Root-> lchild = createbitree (2 * I, n ); else root-> LCH ILD = NULL; If (2 * I + 1 <= N) Root-> rchild = createbitree (2 * I + 1, n); else root-> rchild = NULL; return root;}/***********************/void preorder (bitree * root) {If (root = NULL) return; printf ("% d", root-> NO); preorder (root-> lchild); preorder (root-> rchild ); return;} void inorder (bitree * root) {If (root = NULL) return; inorder (root-> lchild); printf ("% d ", root-> NO); inorder (root-> rchild); return ;} Void postorder (bitree * root) {If (root = NULL) return; postorder (root-> lchild); postorder (root-> rchild); printf ("% d ", root-> NO); return ;} /************************/void noorder (bitree * root) {sequeue * sq; sq = createemptysequeue (); ensequeue (SQ, root); While (! Emptysequeue (SQ) {root = desequeue (SQ); printf ("% d", root-> NO); If (root-> lchild! = NULL) ensequeue (SQ, root-> lchild); If (root-> rchild! = NULL) ensequeue (SQ, root-> rchild);} return;} int main () {bitree * root; root = createbitree (1, 10); printf ("preorder: "); preorder (Root); printf (" \ n "); printf (" inorder: "); inorder (Root); printf (" \ n "); printf ("postorder:"); postorder (Root); printf ("\ n"); printf ("noorder:"); noorder (Root ); printf ("\ n"); Return 0 ;}