The binary tree traversal method of implementation and three kinds - Code

. 1 #include <stdio.h>
 2 #include <stdlib.h>
 . 3  
. 4  / * datatype tree * / 
. 5 typedef char TElemType;
 . 6  / * definition of binary tree structure * / 
. 7 typedef struct BiTNode
 . 8  {
 . 9      TElemType Data;                     // data 
10      struct BiTNode left *, right *;        // left child node 
. 11 } BiTNode, * BiTree;
 12 is  
13 is  void createBiTree (BiTree * T)
 14  {
 15      char ch;
16     scanf("%c",&ch);
17     if(ch ==' ')
18     {
19         *T = NULL;
20     }
21     else
22     {
23         *T = (BiTNode*)malloc(sizeof(BiTNode));
24         if(!*T) exit(-1);
25         (*T)->data = ch;
26         createBiTree(&(*T)->left);
27         createBiTree(&(*T)->right);
28     }
29     
30 }
31 
32 void preOrder(BiTree T)
33 {
34     if(T==NULL) return;
35     printf("%c",T->data);
36     preOrder(T->left);
37     preOrder(T->right);
38 }
39 
40 void InOrder(BiTree T)
41 {
42     if(T==NULL)return ;
43     InOrder(T->left);
44     printf("%c",T->data);
45     InOrder(T->right);
46 }
47 
48 void PostOrder(BiTree T)
49 {
50     if(T==NULL)return;
51     PostOrder(T->left);
52     PostOrder(T->right);
53     printf("%c",T->data);
54 }
55 
56 int main(int argc, char const *argv[])
57 {
58      BiTree T;
 59      createBiTree (& T);
 60      the printf ( " preorder: \ n- " );
 61 is      preOrder (T);
 62 is      the printf ( " \ n-traversal sequence: \ n- " );
 63 is      the InOrder (T) ;
 64      the printf ( " \ n after preorder: \ n " );
 65      postorder (T);
 66      // the ABC GF DE    
67      return  0 ;
 68 }

result:

 

 Note: chcp 65001 Chinese garbled solve the output terminal.

 

A detailed analysis of the code tree for the next one.

 

                          

 

 

Guess you like

Origin www.cnblogs.com/ambdyx/p/11984776.html