Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MATEUSZ ZAMARLIK
- // 2017-02-28
- // Lista 1 - Zadanie 4 - Drzewa binarne
- /* Zadanie 4. Zdefiniuj własny typ DrzewoBinarne reprezentujące drzewo
- binarnych poszukiwań. DrzewoBinarne przechowujące w węzłach struktury
- ustalonego typu str wraz z procedurami wstawiania i wyszukiwania elementów
- w drzewie. Zaprogramuj również funkcję int rozmiar zwracającą liczbę
- elementów drzewa. */
- // DYGRESJA
- /* zakladam, ze drzewo sie w zadnym punkcie nie zapetla, a wezly wystepuja
- w drzewie jednorazowo tj. nie ma dwoch galezi dochodzacych do tego
- samego elementu */
- #include <stdlib.h>
- #include <string.h>
- typedef struct binary_t {
- struct binary_t* left;
- char* str;
- struct binary_t* right;
- } BinaryTree;
- // FUNKCJA WYSZUKIWANIA
- BinaryTree* search_tree(char* str, BinaryTree* tree) {
- if(tree==NULL) return NULL;
- while(strcmp(str,tree->str)!=0) {
- if(strcmp(str,tree->str)<0)
- if(tree->left!=NULL) tree=tree->left;
- else {return NULL;}
- else {
- if(tree->right!=NULL) tree=tree->right;
- else {return NULL;}
- }
- }
- return tree;
- }
- // FUNKCJA WSTAWIANIA
- void insert_into_tree(char* str, BinaryTree *tree) {
- BinaryTree* elem;
- elem=(BinaryTree*)calloc(1,sizeof(BinaryTree));
- if(search_tree(str,tree)==NULL) {
- elem->str=str;
- if(tree==NULL) {
- tree=elem;
- }
- else while(strcmp(str,tree->str)!=0) {
- if(strcmp(str,tree->str)<0)
- if(tree->left!=NULL) tree=tree->left;
- else {
- tree->left=elem;
- break;
- }
- else {
- if(tree->right!=NULL) tree=tree->right;
- else {
- tree->right=elem;
- break;
- }
- }
- }
- } else {free(elem); }
- }
- // FUNKCJA LICZACA ROZMIAR
- int size_of_tree(BinaryTree* tree) {
- int result=1;
- if(tree==NULL) return 0;
- if(tree->left!=NULL) result+=size_of_tree(tree->left);
- if(tree->right!=NULL) result+=size_of_tree(tree->right);
- return result;
- }
- void print_tree(BinaryTree *tree) {
- if(tree=NULL) puts("Tree is empty.");
- else {
- printf("%s",tree->str);
- if(tree->left!=NULL) {
- printf("Left branch: ");
- printt_tree()
- }
- }
- }
- int main(void) {
- BinaryTree *root = NULL;
- insert_into_tree("abc",&root);
- insert_into_tree("ab",&root);
- insert_into_tree("bc",&root);
- insert_into_tree("abbc",&root);
- printf("Size: %d",size_of_tree(root));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement