Advertisement
AsimKPrasad

Binary Tree : Odd-Even level Sum

Nov 22nd, 2014
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. /*
  2.  
  3.     Author :    Asim Krishna Prasad
  4.  
  5.     Program to get the sum of the nodes on the even level and odd level
  6.     in a binary tree
  7.  
  8.     Note : Taking the level of root as 0
  9.             Uncomment the commented codes to understand the execution better
  10.  
  11. */
  12.  
  13. #include<stdio.h>
  14. #include<stdlib.h>
  15.  
  16. #define scan(a)     scanf("%d", &a)
  17. #define print(a)    printf("%d", a)
  18. #define nline       printf("\n")
  19. #define fl(i,a,b)   for(i=a; i<b; i++)
  20.  
  21. struct node
  22. {
  23.     int data;
  24.     struct node* right, *left;
  25. };
  26.  
  27. struct node* root=NULL;
  28. struct node* end=NULL;
  29.  
  30. int arr[2];
  31.  
  32. struct node* insert(int ndata, struct node* curr)
  33. {
  34.    
  35.     if(curr==NULL)
  36.     {
  37.         //printf("inserting here"); nline;
  38.         struct node* temp;
  39.         temp=(struct node*)(malloc(sizeof(struct node)));
  40.         temp->data=ndata;
  41.         temp->left=temp->right=NULL;
  42.         curr=temp;
  43.         //printf("returning from insertion now"); nline;
  44.         return curr;
  45.     }
  46.     if(curr->data>ndata)
  47.     {
  48.         //printf("going to the left child"); nline;
  49.         curr->left=insert(ndata,curr->left);
  50.         //printf("coming back after inserting to the left child"); nline;
  51.     }
  52.        
  53.     else
  54.     {
  55.         //printf("going to the right child"); nline;
  56.         curr->right=insert(ndata,curr->right);
  57.         //printf("coming back after inserting to the right child"); nline;
  58.     }
  59.     return curr;
  60. }
  61.  
  62. void traverse(struct node* curr, int level)
  63. {
  64.     if(curr==NULL)
  65.         return;
  66.     traverse(curr->left, level+1);
  67.     //print(curr->data); printf(" "); print(level); nline;
  68.     arr[level%2]+=curr->data;
  69.     traverse(curr->right, level+1);
  70. }
  71.  
  72. int main()
  73. {
  74.     int n, m, i, j, k;
  75.     printf("Enter the number of nodes to be inserted : ");
  76.     scan(n);
  77.     printf("Enter the elements one-by-one : \n");
  78.     fl(i,0,n)
  79.     {
  80.         scan(k);
  81.         root=insert(k,root);
  82.     }
  83.     traverse(root, 0);
  84.     printf("Sum of the nodes on the even levels : "); print(arr[0]); nline;
  85.     printf("Sum of the nodes on the odd levels : "); print(arr[1]); nline;
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement