1// Aim: Program to perform Binary Tree operations (Array representation).
2#include <stdio.h>
3#include <stdlib.h>
4int a[15], i, item, key, ch, loc;
5void display() {
6 for (i = 0; i < 15; i++) {
7 if (a[i] != -1) {
8 printf("%d ", a[i]);
9 } else {
10 printf("- ");}}
11 printf("\n");}
12
13
14void build(int index) {
15 if (index >= 15)
16 return;
17 printf("\nEnter item: ");
18 scanf("%d", &a[index]);
19 printf("\nWant to create left child for %d? If yes, enter 0: ", a[index]);
20 scanf("%d", &ch);
21 if (ch == 0) {
22 build(2 * index + 1);}
23 printf("\nWant to create right child for %d? If yes, enter 0: ", a[index]);
24 scanf("%d", &ch);
25 if (ch == 0) {
26 build(2 * index + 2);}}
27
28
29int search(int index) {
30 if (index < 15) {
31 if (a[index] == key) {
32 loc = index;
33 return 1;
34 } else {
35 if (search(2 * index + 1) || search(2 * index + 2)) {
36 return 1;}}}
37 return 0;}
38
39
40void insert() {
41 printf("\nEnter item to insert: ");
42 scanf("%d", &item);
43 printf("\nWant to insert %d as left child of %d? If yes, enter 0: ", item, key);
44 scanf("%d", &ch);
45 if (ch == 0) {
46 if (a[2 * loc + 1] == -1) {
47 a[2 * loc + 1] = item;
48 } else {
49 printf("\nLeft child exists");}
50 } else {
51 printf("\nWant to insert %d as right child of %d? If yes, enter 0: ", item, key);
52 scanf("%d", &ch);
53 if (ch == 0) {
54 if (a[2 * loc + 2] == -1) {
55 a[2 * loc + 2] = item;
56 } else {
57 printf("\nRight child exists");}}}}
58
59
60void delete() {
61 printf("\nEnter key to delete: ");
62 scanf("%d", &key);
63 loc = -1;
64 if (search(0)) {
65 if (a[2 * loc + 1] == -1 && a[2 * loc + 2] == -1) {
66 a[loc] = -1;
67 } else {
68 printf("\nNot a leaf, deletion denied");}
69 } else {
70 printf("\nKey not found");}}
71
72
73int main(void) {
74 int choice;
75 for (i = 0; i < 15; i++) {
76 a[i] = -1;}
77 while (1) {
78 printf("\nMenu:\n");
79 printf("1. Build Tree\n2. Display Tree\n3. Search Key\n4. Insert Item\n5. Delete Item\n6. Exit\nEnter your choice: ");
80 scanf("%d", &choice);
81 switch (choice) {
82 case 1:
83 build(0);
84 break;
85 case 2:
86 printf("Tree is:\n");
87 display();
88 break;
89 case 3:
90 printf("\nEnter key to search: ");
91 scanf("%d", &key);
92 loc = -1;
93 if (search(0))
94 printf("\nKey found at index %d....", loc);
95 else
96 printf("\nKey not found....");
97 break;
98 case 4:
99 printf("\nEnter key to search for insertion: ");
100 scanf("%d", &key);
101 loc = -1;
102 if (search(0)) {
103 insert();
104 } else {
105 printf("\nKey not found, cannot insert");}
106 break;
107 case 5:
108 delete();
109 break;
110 case 6:
111 exit(0);
112 default:
113 printf("Invalid choice! Please enter a valid option.\n");}}
114 return 0;}