You are on page 1of 3

typedef struct NODE { int data; NODE* left; NODE* right; }; typedef struct NODE* TREE; TREE root;

// Ham tao cay nhi phan

void CreateTREE(TREE &root) { int x; printf("\nNhap gia tri node :"); scanf("%d",&x); if (x!=0) { root=(NODE*)malloc(sizeof(NODE)); root ->data=x; printf("\n Con trai cua %d (Enter 0)",x); CreateTREE(root->left); printf("\n Con phai cua %d (Enter 0)",x); CreateTREE(root->right); } else root=NULL; }

//Tim node, co thi tra ve dia chi khong thi tra ve NULL
TREE timkiem(TREE root, int x) { TREE p; if (root==NULL) return NULL; else { if (root->data==x) return root; { p=timkiem(root->left,x); if (p!=NULL) return p; return timkiem(root->right,x); } } }

// ham tra ve so nut la cua cay


int demla(TREE root) { if(root==NULL) return NULL; if ((root->left==NULL)&&(root->right==NULL)) return 1+ demla(root->left)+demla(root->right); return demla(root->left)+demla(root->right); } 1

// Them mot node vao cay


void Add(int x,TREE &root) { if(root==NULL) { TREE p; p=(TREE)malloc(sizeof(NODE)); p->data=x; p->Left=p->Right=NULL; root=p; } else if(x!=root->data) { if(x<root->data) Add(x,root->Left); else Add(x,root->Right); } }

//Tim kiem node co khoa x


TREE search(int x,TREE root) { if(root==NULL) return NULL ; if(root->data==x) return root; if (root->data>x) return search(x,root->Left); else return search(x,root->Right); }

//tim, khong co thi them vao


void timthaythe(TREE root, int key) { printf("Nhap phan tu can tim kiem:"); scanf("%d",&key); if(search(key,root)!=NULL) printf("Da ton tai"); else { printf("\nPhan tu khong ton tai -> da them vao"); Add(key,root); } }

// xoa cac nut la cua cay

void delnodela(TREE &root) { if (root==NULL) return; if (root->Left==NULL && root->Right==NULL) { delete root; root=NULL; return; } delnodela(root->Left); delnodela(root->Right); }

// so node nhanh cua cay


int sonhanh(TREE &root) { if (root==NULL || ((root->Left==NULL) && (root ->Right==NULL))) return 0; else return 1+sonhanh(root->Left)+sonhanh(root->Right); }

You might also like