Implement recursive traversal of Binary Trees in ascending, central, and descending order using C language
# Include
# Include
// ***** Binary Tree binary linked list storage represents ***** // typedef struct BiNode {char data; struct BiNode * lchild, * rchild;} BiNode, * BiTree; // ***** enter the node value (one character) in the binary tree in the FIFO order ), the space character indicates that the empty tree constructs the binary tree T ***** represented by the binary chain table. // void CreateBiTree (BiTree & T) {char ch; scanf ("% c ", & ch); if (ch = '') {T = NULL;} else {if (! (T = (BiNode *) malloc (sizeof (BiNode) {return;} T-> data = ch; // generate the root node CreateBiTree (T-> lchild ); // construct the left subtree CreateBiTree (T-> rchild); // construct the right subtree} return ;} // ***** traverse a binary tree in sequence ***** // void PreOrderTraverse (BiTree T) {if (! T) {return; // If T is an empty tree, it will return} printf ("% c", T-> data ); // access the root node PreOrderTraverse (T-> lchild); // first traverse the left subtree PreOrderTraverse (T-> rchild); // first traverse the right subtree return ;} // ****** central order traversal Binary Tree ***** // void InOrderTraverse (BiTree T) {if (! T) {return; // If T is an empty tree, return directly} InOrderTraverse (T-> lchild); // traverse the left subtree printf ("% c ", t-> data); // access the root node InOrderTraverse (T-> rchild); // traverse the right subtree return in the middle order ;} // ***** post-order traversal of a binary tree ***** // void PostOrderTraverse (BiTree T) {if (! T) {return; // If T is an empty tree, return directly} PostOrderTraverse (T-> lchild); // traverse the left subtree PostOrderTraverse (T-> rchild) in a descending order ); // traverse the right subtree printf ("% c", T-> data) in a descending order; // access the root node return;} int main (void) {BiTree T; printf ("Enter the node value (character) in the binary tree in the FIFO order, and the space character indicates the empty tree: \ n"); CreateBiTree (T ); printf ("result of first-order traversal:"); PreOrderTraverse (T); printf ("\ n"); printf ("result of Middle-order traversal :"); inOrderTraverse (T); printf ("\ n"); printf ("the result of post-order traversal is:"); PostOrderTraverse (T ); printf ("\ n"); return 0 ;}
The following binary tree is used as an example to describe the value (character) of the node input in the binary tree in the FIFO order, and construct the binary tree according to the algorithm given in this article.
The order of input characters is:-+ a Space * B space-c space d space/e space f space, you can verify the traversal algorithm provided in this Article.