In computer science, a tree is an important nonlinear data structure, visually, it is a structure of data elements (called nodes in a tree) organized by branching relationships. A binary tree is an ordered tree with a maximum of two subtrees per node. The subtree is often referred to as the left subtree and the right subtree (subtree). Binary trees are often used to implement a two-fork search tree and a two-fork heap.
Here is the code that implements the sequence traversal of creating a two-fork tree and a two-fork tree:
1#include <stdio.h>2#include <stdlib.h>3#include <memory.h>4 5typedefstruct_tree_node{6 Chardata;7 struct_tree_node *Left ;8 struct_tree_node *Right ;9 struct_tree_node *father;Ten }tree_node; One A voidCreatetree (Tree_node *root); - voidInordertraversetree (Tree_node *proot); - the intMain () - { - Tree_node Root; -memset (&root,0,sizeof(Tree_node)); +printf"Please create the tree: \ n"); -Createtree (&root); +printf"The inorder traverse result is: \ n"); AInordertraversetree (&root); at return 0; - } - - //inorder Traversal - voidInordertraversetree (Tree_node *proot) - { inTree_node * Pcur =Proot; - if(Pcur! =NULL) to { + if(Pcur->left! =NULL) - { theInordertraversetree (pcur->Left ); * } $ ElsePanax Notoginseng { -printf"%c", pcur->data); the return; + } Aprintf"%c", pcur->data); the + if(Pcur->right! =NULL) - { $Inordertraversetree (pcur->Right ); $ } - } - } the - //Create the binary treeWuyi voidCreatetree (Tree_node *proot) the { - CharCH =0; WuTree_node * Pcur =Proot; - while(ch = getchar ())! ='e') About { $ //printf ("%c", ch); -Tree_node * Pnewnode = (Tree_node *) malloc (sizeof(Tree_node)); -Pnewnode->left =NULL; -Pnewnode->right =NULL; APnewnode->father =NULL; + if(ch = ='L') the { - //printf ("Input l\n"); $Pnewnode->data =GetChar (); thePnewnode->father =pcur; thePcur->left =Pnewnode; thePcur =Pnewnode; the } - Else if(ch = ='R') in { the //printf ("Input r\n"); thePnewnode->data =GetChar (); AboutPnewnode->father =pcur; thePcur->right =Pnewnode; thePcur =Pnewnode; the } + Else if(ch = ='B') - { the //printf ("Input b\n");Bayi Free (pnewnode); the if(Pcur->father! =NULL) thePcur = pcur->father; - Else -printf"It ' s the top\n"); the } the } the}
Construct such a binary tree:
The result of the program operation is: