Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include<stdio.h>
- #include<stdlib.h>
- //#include<iostream.h>
- int a[7]={ 5,10,51,61,15,20,21};
- struct tree
- {
- int max,min,dmax,dmin;
- struct tree *left;
- struct tree *right;
- struct tree *baap;
- };
- typedef struct tree *ptr;
- ptr root= NULL;
- ptr present=NULL;
- int max(int a, int b)
- {
- return a>b?a:b;
- }
- int depth(ptr node)
- {
- if(node == NULL)
- {
- return 0;
- }
- return max(depth(node->left) +1,depth(node->right) +1);
- }
- ptr maketree()
- {
- ptr p;
- p=(ptr)malloc(sizeof(struct tree));
- p->left=NULL;
- p->right=NULL;
- p->dmax=0;
- p->dmin=0;
- if(p==NULL)
- {
- printf("cannot create\n");
- return NULL;
- }
- else
- return p;
- }
- void create(ptr q)
- {
- int mid;
- if((q->max-q->min) > 1)
- {
- mid= (q->max + q->min)/2;
- ptr x,y;
- x=maketree();
- y=maketree();
- x->min=q->min;
- x->max=mid;
- y->min=mid+1;
- y->max=q->max;
- q->left=x;
- q->right=y;
- create(q->left);
- create(q->right);
- }
- }
- void filldata(ptr q)
- {
- if(q->left==NULL && q->right== NULL)
- {
- q->dmax= a[q->max];
- q->dmin=a[q->min];
- if(q->dmax < q->dmin)
- {
- int t;
- t=q->dmax;
- q->dmax=q->dmin;
- q->dmin=t;
- }
- }
- else
- {
- int big, small;
- ptr x,y;
- x=q->left;
- y=q->right;
- if(x->dmax > y->dmax )
- {
- big=x->dmax;
- }
- else
- big=y->dmax;
- if(x->dmin < y->dmin )
- {
- small=x->dmin;
- }
- else
- small=y->dmin;
- q->dmax= big;
- q->dmin=small;
- }
- }
- void traverse(ptr q)
- {
- if(q!=NULL)
- {
- filldata(q);
- traverse(q->left);
- traverse(q->right);
- }
- }
- void display(ptr abc)
- {
- if(abc!=NULL)
- {
- //printf("%d ",abc->info);
- printf("\n\n%d \t%d", abc->max+1, abc->min+1);
- printf("\n%d\t%d", abc->dmax, abc->dmin);
- display(abc->left);
- display(abc->right);
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- int n,i;
- ptr root;
- printf("\nenter the number of elements: ");
- scanf("%d",&n);
- printf("\nEnter the array: ");
- for(i=0;i<n;i++)
- scanf("%d",&a[i]);
- root=maketree();
- root->max=n-1;
- root->min=0;
- create(root);
- int deep;
- deep= depth(root);
- for(i=0;i<deep;i++)
- {
- traverse(root);
- }
- printf("\n\nThe tree in preorder is \nMax\t\tMin\nData[MAX]\tData[min]");
- display(root);
- system("pause");
- return 0;
- }
- /*
- enter the number of elements: 7
- Enter the array: 5 10 51 61 15 20 21
- The tree in preorder is
- Max Min
- Data[MAX] Data[MIN]
- 7 1
- 61 5
- 4 1
- 61 5
- 2 1
- 10 5
- 4 3
- 61 51
- 7 5
- 21 15
- 6 5
- 20 15
- 7 7
- 21 21Press any key to continue . . .
- */
Advertisement
Add Comment
Please, Sign In to add comment