diff --git a/mytree.c b/mytree.c new file mode 100644 index 0000000000000000000000000000000000000000..b10f9c228adec3e8c41513a48e5ae837d45023c5 --- /dev/null +++ b/mytree.c @@ -0,0 +1,96 @@ +#include<stdlib.h> +#include<stdio.h> +#include<stdbool.h> //to return true and false + + +struct Node{ //[left|data|right] + int data; + struct Node* left; + struct Node* right; +}; + +////////////////////////////////////////////// NODE-FUNCTION + +struct Node* CreateFunc(int data){ +struct Node* new_Node=(struct Node*)malloc(sizeof(struct Node)); + new_Node->data=data; + new_Node->left=NULL; + new_Node->right=NULL; + return new_Node; +} +//////////////////////////////////////////////INSERT-FUNCTION + +struct Node* Insert(struct Node* root,int data) { + if(root == NULL){ + root = CreateFunc(data); //root saves the address of the created node + return root; //returns the address to Insert + } + + else if(data <= root->data) { + root->left = Insert(root->left,data); + return root; + } + + else { + root->right = Insert(root->right,data); + return root; + } +} + +////////////////////////////////////////////// SEARCH-FUNCTION + +bool iSearch(struct Node* root,int data) { + if(root == NULL) { + return false; + } + else if(root->data == data) { + return true; + } + else if(data <= root->data) { + return iSearch(root->left,data); + } + else { + return iSearch(root->right,data); + } +} + +int main() { + int myArray[5]; + int i=0; + printf("Please enter 5 numbers:\n"); + + do{ + scanf("%d",&myArray[i]); + i++;} + while(i!=5); + + struct Node* root = NULL; + root = Insert(root,myArray[0]); //updates the address of root + root = Insert(root,myArray[1]); + root = Insert(root,myArray[2]); + root = Insert(root,myArray[3]); + root = Insert(root,myArray[4]); + + for(int i=0; i<5;i++){ //to find the maximum of my array + if(myArray[0]<myArray[i]) + myArray[0]=myArray[i]; + } + int max=myArray[0]; + +////////////////////////////////////////////// PRINT-FUNCTION + + int number; + printf("Enter the number you look for:\n"); + scanf("%d",&number); + if(iSearch(root,number) == true) + printf("\nTrue\n"); + + else printf("\nFalse"); + + printf("\n\n["); + for(int i = 1; i<=max; i++){ + if(iSearch(root,i)==true) + printf("%d%s",i,(i==max)?"":","); + } + printf("]"); +}