Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Author : Asim Krishna Prasad
- Program to get the sum of the nodes on the even level and odd level
- in a binary tree
- Note : Taking the level of root as 0
- Uncomment the commented codes to understand the execution better
- */
- #include<stdio.h>
- #include<stdlib.h>
- #define scan(a) scanf("%d", &a)
- #define print(a) printf("%d", a)
- #define nline printf("\n")
- #define fl(i,a,b) for(i=a; i<b; i++)
- struct node
- {
- int data;
- struct node* right, *left;
- };
- struct node* root=NULL;
- struct node* end=NULL;
- int arr[2];
- struct node* insert(int ndata, struct node* curr)
- {
- if(curr==NULL)
- {
- //printf("inserting here"); nline;
- struct node* temp;
- temp=(struct node*)(malloc(sizeof(struct node)));
- temp->data=ndata;
- temp->left=temp->right=NULL;
- curr=temp;
- //printf("returning from insertion now"); nline;
- return curr;
- }
- if(curr->data>ndata)
- {
- //printf("going to the left child"); nline;
- curr->left=insert(ndata,curr->left);
- //printf("coming back after inserting to the left child"); nline;
- }
- else
- {
- //printf("going to the right child"); nline;
- curr->right=insert(ndata,curr->right);
- //printf("coming back after inserting to the right child"); nline;
- }
- return curr;
- }
- void traverse(struct node* curr, int level)
- {
- if(curr==NULL)
- return;
- traverse(curr->left, level+1);
- //print(curr->data); printf(" "); print(level); nline;
- arr[level%2]+=curr->data;
- traverse(curr->right, level+1);
- }
- int main()
- {
- int n, m, i, j, k;
- printf("Enter the number of nodes to be inserted : ");
- scan(n);
- printf("Enter the elements one-by-one : \n");
- fl(i,0,n)
- {
- scan(k);
- root=insert(k,root);
- }
- traverse(root, 0);
- printf("Sum of the nodes on the even levels : "); print(arr[0]); nline;
- printf("Sum of the nodes on the odd levels : "); print(arr[1]); nline;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement