The first section of the xinxing algorithm tutorial is the recursive traversal of Binary Trees.
We all know that recursive traversal of Binary trees can be divided into three types: Pre-sequential traversal, middle-order traversal, and post-order traversal. In fact, these three traversal methods are similar, because they are all implemented using recursion, therefore, it is relatively simple.
The first is the tree. h file. The Code is as follows:
#ifndef TREE_H#define TREE_H#include <stdio.h>#include <malloc.h>#include <assert.h>typedef int ElemType;typedef struct Btree{ ElemType val; struct Btree* left; struct Btree* right;}Btree, *Pbtree;#endif
Next is tree. c. The Code is as follows:
# Include <stdio. h> # include <stdlib. h> # include "tree. h "/*** get the value information of a node * @ param Pbtree pNode pointer information */static void BtreeVisit (Pbtree pNode) {if (NULL! = PNode) {printf ("current node value: % d \ n", pNode-> val) ;}}/*** to construct a tree node, leave the Left and Right pointer blank, and return the type of the pointer * @ param ElemType value to the new node * @ return Pbtree pointer to the new node */static Pbtree BtreeMakeNode (ElemType target) {Pbtree pNode = (Pbtree) malloc (sizeof (Btree); assert (NULL! = PNode); pNode-> val = target; pNode-> left = NULL; pNode-> right = NULL; return pNode ;} /*** insert a node information * @ param ElemType the data to be inserted * @ Param Pbtree * pointer to a node * @ return Pbtree pointer to a new node */Pbtree btreeInsert (ElemType target, pbtree * ppTree) {Pbtree pNode; assert (NULL! = PpTree); pNode = * ppTree; if (NULL = pNode) {return * ppTree = BtreeMakeNode (target );} // insert if (pNode-> val = target) {return NULL;} else if (pNode-> val> target) {return BtreeInsert (target, & pNode-> left);} else {return BtreeInsert (target, & pNode-> right );}} /*** traverse the tree in the forward order **/void BtreePreOrder (Pbtree pNode) {if (NULL! = PNode) {BtreeVisit (pNode); BtreePreOrder (pNode-> left); BtreePreOrder (pNode-> right);} int main (int argc, char * argv []) {int I; int num [] = {,}; Pbtree root = NULL; for (I = 0; I <sizeof (num)/sizeof (int ); I ++) {BtreeInsert (num [I], & root);} BtreePreOrder (root); return 0 ;}
Here, our data is differentiated during insertion. If this number is small, it is inserted to the left. If it is greater than this number, it is inserted to the right, the final insert structure should be as follows:
21
2 43
6 88
9
The output order is 21 2 6 9 43 88.