Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <fstream>
- using namespace std;
- struct Node
- {
- int data;
- Node *firstChild;
- Node *nextSibling;
- Node(int d, Node *f, Node *n)
- {
- data=d;
- firstChild=f;
- nextSibling=n;
- }
- };
- typedef struct TreeADT *Tree;
- struct TreeADT
- {
- Node *root;
- };
- void createTop(Node *p, Node *pp, int arr[], int index, int n)
- {
- if (arr[index]==pp->data)
- {
- Node *pt = new Node(arr[index+1],NULL,NULL);
- pp->firstChild=pt;
- createTop(pp,pt,arr,index+2,n);
- }
- for (int i=index;i<n;i=i+2)
- {
- if (arr[i]==p->data)
- {
- Node *pt= new Node(arr[i+1],NULL,NULL);
- pp->nextSibling=pt;
- createTop(p,pt,arr,i+2,n);
- break;
- }
- }
- }
- Tree createTree(char *filename)
- {
- ifstream input(filename);
- Tree list = new TreeADT;
- list->root=NULL;
- if (!input.is_open())
- cout<<"Khong the mo file"<<endl;
- else
- {
- int n=0, arr[100];
- while (input>>arr[n])
- n++;
- Node *p = new Node(arr[0],NULL,NULL);
- Node *pp = new Node(arr[1],NULL,NULL);
- p->firstChild=pp;
- createTop(p,pp,arr,2,n);
- list->root=p;
- }
- return list;
- }
- void Preorder(Tree t)
- {
- if (t->root!=NULL)
- {
- cout<<" "<<t->root->data;
- Tree p = new TreeADT;
- p->root=t->root->firstChild;
- while (p->root!=NULL)
- {
- Preorder(p);
- p->root=p->root->nextSibling;
- }
- }
- }
- void Postorder(Tree t)
- {
- if (t->root!=NULL)
- {
- Tree p = new TreeADT;
- p->root=t->root->firstChild;
- while (p->root!=NULL)
- {
- Postorder(p);
- p->root=p->root->nextSibling;
- }
- cout<<" "<<t->root->data;
- }
- }
- int main(int argc, char const *argv[])
- {
- char filename[]="data_01.txt";
- Tree t=createTree(filename);
- Preorder(t);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment