Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <conio.h>
- #include <malloc.h>
- struct tree
- {
- int data;
- struct tree *left, *right;
- };
- typedef struct tree node;
- node *root;
- void insert(void);
- void search(void);
- void inorder(node *ptr);
- void preorder(node *ptr);
- void postorder(node *ptr);
- int main()
- {
- int c;
- clrscr();
- do
- {
- printf("\n press 1 for insert");
- printf("\n press 2 for search");
- printf("\n press 3 for inorder ");
- printf("\n press 4 for preorder ");
- printf("\n press 5 for postorder ");
- printf("\n press 0 for exit");
- scanf("%d", &c);
- if (c == 1)
- {
- insert();
- }
- else if (c == 2)
- {
- search();
- }
- else if (c == 3)
- {
- inorder(root);
- }
- else if (c == 4)
- {
- preorder(root);
- }
- else if (c == 5)
- {
- postorder(root);
- }
- } while (c != 0);
- getch();
- return 0;
- }
- void insert(void)
- {
- int f = 0;
- node *temp, *ptr, *parent;
- temp = (node *)malloc(sizeof(node));
- printf("\n enter any number");
- scanf("%d", &temp->data);
- temp->left = NULL;
- temp->right = NULL;
- if (root == NULL)
- {
- root = temp;
- }
- else
- {
- ptr = root;
- while (ptr->data != temp->data)
- {
- parent = ptr;
- if (temp->data < ptr->data)
- {
- ptr = ptr->left;
- if (ptr == NULL)
- {
- f = 1;
- break;
- }
- }
- else if (temp->data > ptr->data)
- {
- ptr = ptr->right;
- if (ptr == NULL)
- {
- f = 2;
- break;
- }
- }
- else if (ptr->data == temp->data)
- {
- printf("\n node already exist");
- }
- }
- }
- if (f == 1)
- {
- parent->left = temp;
- }
- else if (f == 2)
- {
- parent->right = temp;
- }
- }
- void search()
- {
- node *ptr;
- int c;
- printf("\n enter tthe number for search");
- scanf("%d", &c);
- ptr = root;
- while (ptr->data != c)
- {
- printf("\n %d", ptr->data);
- if (c < ptr->data)
- {
- ptr = ptr->left;
- if (ptr == NULL)
- {
- printf("\nnodenot found in the list");
- break;
- }
- }
- else if (c > ptr->data)
- {
- ptr = ptr->right;
- if (ptr == NULL)
- {
- printf("\n nodeis not found in the list");
- break;
- }
- }
- else if (c == ptr->data)
- {
- printf("\n no. isfound in the list");
- }
- }
- }
- void inorder(node *ptr)
- {
- if (ptr != NULL)
- {
- inorder(ptr->left);
- printf("\t %d", ptr->data);
- inorder(ptr->right);
- }
- }
- void preorder(node *ptr)
- {
- if (ptr != NULL)
- {
- printf("\t %d", ptr->data);
- preorder(ptr->left);
- preorder(ptr->right);
- }
- }
- void postorder(node *ptr)
- {
- if (ptr != NULL)
- {
- postorder(ptr->left);
- postorder(ptr->right);
- printf("\t %d", ptr->data);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement