amanjain110893

reverse level order

Sep 28th, 2014
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef struct TreeNode{
  6.     int val;
  7.     TreeNode *left,*right;
  8.     TreeNode(int v){
  9.         val=v;
  10.         left=right=NULL;
  11.     }
  12. }TreeNode;
  13. typedef struct ListNode{
  14.     TreeNode* val;
  15.     ListNode* next;
  16.     ListNode(TreeNode* v){
  17.         val=v;
  18.         next=NULL;
  19.     }
  20. }ListNode;
  21.  
  22. typedef struct Hash{
  23.     ListNode *head,*tail;
  24.     Hash(){
  25.         head=tail=NULL;
  26.     }
  27. }Hash;
  28.  
  29. Hash ar[100];
  30.  
  31. int level;
  32. TreeNode* insert(TreeNode* root,int v){
  33.     if(root==NULL){
  34.         return root=new TreeNode(v);
  35.     }
  36.     if(root->val<v){
  37.         root->right=insert(root->right,v);
  38.     }
  39.     else root->left=insert(root->left,v);
  40.     return root;
  41. }
  42. void add(ListNode** head,ListNode** tail,TreeNode* v){
  43. //    printf("%d\n",v->val);
  44.     if(*head==NULL){
  45.         *head=new ListNode((v));
  46.         *tail=*head;
  47.         return;
  48.     }
  49.     (*tail)->next=new ListNode((v));
  50.     *tail=(*tail)->next;
  51. }
  52.  
  53. void rev(TreeNode *root){
  54.     if(root==NULL){
  55.         return;
  56.     }
  57.     int co;
  58.     add(&ar[0].head,&ar[0].tail,root);
  59.     ++level;
  60.     while(1){
  61.         co=0;
  62.         for(ListNode* t=ar[level-1].head;t;t=t->next){
  63.             if(t->val->left){
  64.                 add(&ar[level].head,&ar[level].tail,t->val->left);
  65.                 ++co;
  66.             }
  67.             if(t->val->right){
  68.                 add(&ar[level].head,&ar[level].tail,t->val->right);
  69.                 ++co;
  70.             }
  71.         }
  72.         if(co==0){
  73.             break;
  74.         }
  75. //        printf("%d\n",level);
  76.         ++level;
  77.     }
  78.     return;
  79. }
  80.      
  81. void print(ListNode* head){
  82.     for(;head;head=head->next){
  83.         printf("%d ",head->val->val);
  84.     }
  85.     printf("\n");
  86.     return;
  87. }
  88. void CLR(){
  89.     for(int i=0;i<100;++i){
  90.         ar[i].head=ar[i].tail=NULL;
  91.     }
  92.     return;
  93. }
  94. int main(){
  95.     level=0;
  96.    // CLR();
  97.     int n;
  98.     cin>>n;
  99.     TreeNode* root=NULL;
  100.     for(int i=0;i<n;++i){
  101.         int x;
  102.         cin>>x;
  103.         root=insert(root,x);
  104.     }
  105.     rev(root);
  106.     for(int i=level-1;i>=0;--i){
  107.         print(ar[i].head);
  108.     }
  109.     return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment