#include <stdio.h> #include <stdlib.h> #include <time.h>
//#define INIT 10000
#define INIT 5
//#define TOTAL 100000000
#define TOTAL 10
static int count = 0;
typedef struct tree { int num; struct tree* parent; struct tree* lchild; struct tree* rchild; }TREE; TREE* add_tree(TREE** T, TREE* parent, int num) { if(*T == NULL) { *T = (TREE*)malloc(sizeof(TREE)); if(*T == NULL) { printf("malloc error\n"); return NULL; } printf("added %d\n",num); (*T)->num = num; (*T)->parent = parent; (*T)->lchild = NULL; (*T)->rchild = NULL; } else if((*T)->num < num) return add_tree(&(*T)->rchild,*T,num); else return add_tree(&(*T)->lchild,*T,num); }
int midwalk(TREE* T) { if(T!=NULL) { midwalk(T->lchild); count++; if(count%10 == 0) { count = 0; printf("%d\n",T->num); } else printf("%d\t",T->num); midwalk(T->rchild); } return 0; }
int tree_out(TREE** T) { int num = 0; TREE* p = NULL; TREE* q = NULL; TREE** tmp = T; TREE* tmp1 = *T; printf("tmp is %p\ntmp1 is %p\n",*tmp,tmp1); if(*tmp == NULL) { printf("sorry the tree is empty\n"); return -1; } if((*tmp)->lchild == NULL) { q = *tmp; num = q->num; *tmp = (*tmp)->rchild; printf("now head is %d\n",q->num); free(q); q = NULL; return num; } #if 1 while(tmp1->lchild != NULL) { p = tmp1; tmp1 = tmp1->lchild; } p->lchild = tmp1->rchild; num = tmp1->num; free(tmp1); #endif #if 0 while((*tmp)->lchild != NULL) { p = *tmp; *tmp = (*tmp)->lchild; } p->lchild = (*tmp)->rchild; num = (*tmp)->num; free(*tmp); #endif return num; }
int minimum(TREE* T) { while(T->lchild != NULL) { T = T->lchild; } return T->num; } int main(int argc, char *argv[]) { int i = 0; int num = 0; double j = INIT; int mini = 0; TREE* T = NULL; srand( (unsigned)time( NULL ) ); for(i=0;i<INIT;i++) { num = rand(); add_tree(&T, NULL, num); } midwalk(T); mini = minimum(T); for(j=INIT;j<TOTAL;j++) { num = rand(); if(num > mini) { tree_out(&T); add_tree(&T, NULL, num); mini = minimum(T); } } midwalk(T); system("PAUSE"); return 0; }
|