Duclv

Untitled

Oct 28th, 2013
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <fstream>
  4.  
  5. using namespace std;
  6.  
  7. struct Node
  8. {
  9.     int data;
  10.     Node *firstChild;
  11.     Node *nextSibling;
  12.     Node(int d, Node *f, Node *n)
  13.     {
  14.         data=d;
  15.         firstChild=f;
  16.         nextSibling=n;
  17.     }
  18. };
  19.  
  20. typedef struct TreeADT *Tree;
  21. struct TreeADT
  22. {
  23.     Node *root;
  24. };
  25.  
  26. void createTop(Node *p, Node *pp, int arr[], int index, int n)
  27. {
  28.     if (arr[index]==pp->data)
  29.     {
  30.         Node *pt = new Node(arr[index+1],NULL,NULL);
  31.         pp->firstChild=pt;
  32.         createTop(pp,pt,arr,index+2,n);
  33.     }
  34.     for (int i=index;i<n;i=i+2)
  35.     {
  36.         if (arr[i]==p->data)
  37.         {
  38.             Node *pt= new Node(arr[i+1],NULL,NULL);
  39.             pp->nextSibling=pt;
  40.             createTop(p,pt,arr,i+2,n);
  41.             break;
  42.         }
  43.     }
  44. }
  45.  
  46. Tree createTree(char *filename)
  47. {
  48.     ifstream input(filename);
  49.     Tree list = new TreeADT;
  50.     list->root=NULL;
  51.  
  52.     if (!input.is_open())
  53.         cout<<"Khong the mo file"<<endl;
  54.     else
  55.     {
  56.         int n=0, arr[100];
  57.         while (input>>arr[n])
  58.             n++;
  59.         Node *p = new Node(arr[0],NULL,NULL);
  60.         Node *pp = new Node(arr[1],NULL,NULL);
  61.         p->firstChild=pp;
  62.         createTop(p,pp,arr,2,n);
  63.         list->root=p;
  64.     }
  65.     return list;
  66. }
  67.  
  68. void Preorder(Tree t)
  69. {
  70.     if (t->root!=NULL)
  71.     {
  72.         cout<<" "<<t->root->data;
  73.         Tree p = new TreeADT;
  74.         p->root=t->root->firstChild;
  75.         while (p->root!=NULL)
  76.         {
  77.             Preorder(p);
  78.             p->root=p->root->nextSibling;
  79.         }
  80.     }
  81. }
  82.  
  83. void Postorder(Tree t)
  84. {
  85.     if (t->root!=NULL)
  86.     {
  87.         Tree p = new TreeADT;
  88.         p->root=t->root->firstChild;
  89.         while (p->root!=NULL)
  90.         {
  91.             Postorder(p);
  92.             p->root=p->root->nextSibling;
  93.         }
  94.         cout<<" "<<t->root->data;
  95.     }
  96. }
  97.  
  98. int main(int argc, char const *argv[])
  99. {
  100.     char filename[]="data_01.txt";
  101.     Tree t=createTree(filename);
  102.     Preorder(t);
  103.     return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment