0 0 practice503 Asked: November 20, 20212021-11-20T09:09:32+05:30 2021-11-20T09:09:32+05:30In: Data Structure C Program for Depth First Binary Tree Search using Recursion. 0 0 C Program for Depth First Binary Tree Search using Recursion. Share Facebook 1 Answer Voted Oldest Recent Professor 2021-11-20T10:32:15+05:30Added an answer on November 20, 2021 at 10:32 am #include <stdio.h> #include <stdlib.h> struct node { int a; struct node *left; struct node *right; }; void generate(struct node **, int); void DFS(struct node *); void delete(struct node **); int main() { struct node *head = NULL; int choice = 0, num, flag = 0, key; do { printf("\nEnter your choice:\n1. Insert\n2. Perform DFS Traversal\n3. Exit\nChoice: "); scanf("%d", &choice); switch(choice) { case 1: printf("Enter element to insert: "); scanf("%d", &num); generate(&head, num); break; case 2: DFS(head); break; case 3: delete(&head); printf("Memory Cleared\nPROGRAM TERMINATED\n"); break; default: printf("Not a valid input, try again\n"); } } while (choice != 3); return 0; } void generate(struct node **head, int num) { struct node *temp = *head, *prev = *head; if (*head == NULL) { *head = (struct node *)malloc(sizeof(struct node)); (*head)->a = num; (*head)->left = (*head)->right = NULL; } else { while (temp != NULL) { if (num > temp->a) { prev = temp; temp = temp->right; } else { prev = temp; temp = temp->left; } } temp = (struct node *)malloc(sizeof(struct node)); temp->a = num; if (num >= prev->a) { prev->right = temp; } else { prev->left = temp; } } } void DFS(struct node *head) { if (head) { if (head->left) { DFS(head->left); } if (head->right) { DFS(head->right); } printf("%d ", head->a); } } void delete(struct node **head) { if (*head != NULL) { if ((*head)->left) { delete(&(*head)->left); } if ((*head)->right) { delete(&(*head)->right); } free(*head); } } Attachment Leave an answerCancel replyYou must login to add an answer. Username or email* Password* Remember Me! Forgot Password?
1 Answer