Description
The traversal of the tree gives a pointer to the tree, accessing each node in the tree. There are three basic traversal methods for tree traversal, namely pre-order (preorder), middle order (inorder), and post-ordering (postorder).
Recursive Implementation
principle
- Pre-order (preorder): First access the node, and then access the node's Saozi right subtree;
- Middle order (inorder): First access the node's left subtree, then access the node, and then access the node's right subtree;
- Post-postorder: Access the node's Saozi right subtree first, and then access the node.
Code Implementation
#include <stdlib.h>#include <stdio.h>#include <string.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef char ELEMENTTYPE;TYPEDEF int Status;int index =0; char str[] ="abdh#k## #E # #CFI # # #G #j##"; typedef struct treenode{ElementType data; struct TreeNode *left; struct TreeNode *right;} TreeNode, *ptree; Status Inittree (PTree *t) {*t = NULL;returnOK;} Status Visit (PTree T) {if(T = = NULL)returnERROR; printf"%c", T->data);returnOK;}voidDeleteTree (PTree *t) {if(*t) {if((*t)->left) DeleteTree(& (*t)->left);if((*t)->right) DeleteTree(& (*t)->right); Free(*t); *T=NULL; }}void Createtree(PTree *t){ElementType CH;CH=Str[Index++];if(ch = = ' # ')*T=NULL;Else{ *T=(PTree)malloc(sizeof (TreeNode));if((*t) = = NULL) Exit(0);(*t)-data = ch; Createtree(& (*t)->left);Createtree(& (*t)->right); }}int treedepth(PTree T){int ldepth,rdepth;if(T = = NULL) return-1;if(T->left) ldepth=treedepth(T->left);Else ldepth= 0;if(t->right) rdepth=treedepth(t->right);Else rdepth= 0;return (Ldepth > Rdepth)?ldepth+ 1:rdepth+ 1;}int Treenodecount(PTree T){if(T = = NULL) return0;return Treenodecount(T->left)+Treenodecount(t->right)+ 1;}int Treeisempty(PTree T){if(T) return FALSE;Else return TRUE;}void Preordertraverse(PTree T, Status (*visit) (pTree)){if(T = = NULL) return;(*visit) (T); //printf("%c", T->data);Preordertraverse(t->left,visit);Preordertraverse(t->right,visit);}void Inordertraverse(PTree T, Status (*vistit) (pTree)){if(T = = NULL) return;Inordertraverse(t->left,visit);(*visit) (T);Inordertraverse(t->right,visit);}void Postordertraverse(PTree T, Status (*visit) (pTree)){if(T = = NULL) return;Postordertraverse(t->left,visit);Postordertraverse(t->right,visit);(*visit) (T);}int Main(){PTree Tree;Inittree(&tree);Createtree(&tree);printf("Tree ' s Depth is%d\n", treedepth (tree));printf("Tree ' Node number is%d\n", Treenodecount (tree));if(Treeisempty (Tree)){printf("Tree is empty\n"); }printf("Preordertraverse is:");Preordertraverse(tree,visit);printf("\ n");printf("Inordertraverse is:");Inordertraverse(tree,visit);printf("\ n");printf("Postordertraverse is:");Postordertraverse(tree,visit);printf("\ n");DeleteTree(&tree);if(Treeisempty (Tree)){printf("Tree is Delte and empty\n"); }return0;}
The pre-order, the middle order, the sequential traversal (recursion) of the tree