Build a binary tree and traverse sequentially

Problem Description:

 

 

 

Code description:

  1 #include<cstdio>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 #include<queue>
  5 #define MAXN 256
  6 using namespace std;
  7 char s[MAXN+10];
  8 typedef struct Node
  9 {
 10     int h_v;
 11     int v;
 12     struct Node* left;
 13     struct Node* right;
 14 }node,*pt;
15  
16 pt Newnode () // Create a new node 
17  {
 18      pt p = (pt) malloc ( sizeof (node));
 19      p-> h_v = 0 ;
 20      p-> left = p-> right = NULL;
 21      return p;
 22  }
 23  
24 pt root = Newnode ();
 25  
26  void addnode ( int v, char * s)
 27  {
 28      pt p = root;
 29      int n = strlen (s);
 30     for(int i=0;i<n;i++)
 31     {
 32         if(*(s+i)=='L')
 33         {
 34             if(p->left==NULL) 
 35             {
 36                 p->left=Newnode();
 37             }
 38             p=p->left;
 39         }
 40         else if(*(s+i)=='R')
 41         {
 42             if(p-> right == NULL) 
 43              {
 44                  p-> right = Newnode ();
 45              }
 46              p = p-> right;
 47          }
 48      }
 49      if (p-> h_v == 1 )
 50      {
 51          printf ( " Value gives an error multiple times \ n " );
 52          return ;
 53      }
 54      p-> v = v;
 55      p-> h_v = 1 ;
 56  }
 57  
58 void Read_input()
 59 {
 60     while(scanf("%s",&s)==1)
 61     {
 62         if(strcmp(s,"()")==0) break;
 63         int v;
 64         sscanf(s+1,"%d",&v);
 65         addnode(v,strchr(s,',')+1);
 66     }
 67 }
 68 
69  void BFS (pt root)
 70  {
 71      queue <pt> q;
 72      queue < int > ans;
 73      q.push (root);
 74      pt p;
 75      while (! Q.empty ())
 76      {
 77          p = q.front ();
 78          q.pop ();
 79          if (! p-> h_v)
 80          {
 81              printf ( " Null value error \ n " );    // According to the requirements of the question, if there is a node that has not been assigned, an error will be reported exit 
82              return;
 83          }
 84          ans.push (p-> v);
 85          if (p-> left) q.push (p-> left);
 86          if (p-> right) q.push (p-> right);
 87      }
 88      while (! Ans.empty ())
 89      {
 90          printf ( " % d \ t " , ans.front ());
 91          ans.pop ();
 92      }
 93  }
 94  
95  void release (pt root)                 // Free dynamic memory to avoid memory leak 
96  {
 97     if(!root) return;
 98     if(root->left) release(root->left);
 99     if(root->right) release(root->right);
100 }
101 
102 int main()
103 {
104     Read_input();
105     BFS(root);
106     release(root);
107     return 0;
108 }

operation result:

 

 

Guess you like

Origin www.cnblogs.com/bboykaku/p/12711804.html