-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBST.c
More file actions
678 lines (575 loc) · 19.5 KB
/
BST.c
File metadata and controls
678 lines (575 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/*The following code implements a Binary Search Tree (BST) with a few of its basic operations.*/
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
// #define DEBUG 1 // uncomment for memory debug mode or compile with "-DDEBUG" flag
int allocCount = 0;
struct treeNode
{
int data;
struct treeNode *left;
struct treeNode *right;
};
typedef struct treeNode *NODEPTR;
int countNodeBST(NODEPTR); // counts the number of nodes in the tree
void insertNodeBST(NODEPTR*, int); // inserts a node into the tree
void deleteNodeBST(NODEPTR*, NODEPTR*, NODEPTR*, int, int*); // deletes a node from the tree
int countLeafBST(NODEPTR); // counts the number of leaf nodes in the tree
int calcHeightBST(NODEPTR); // calculates the height of the tree
NODEPTR createTree(int); // creates a new binary search tree
void displayInorderBST(NODEPTR); // displays the inorder traversal of the tree
void displayPreorderBST(NODEPTR); // displays the preorder traversal of the tree
void displayPostorderBST(NODEPTR); // displays the post order traversal of the tree
int searchBST(NODEPTR, NODEPTR*, NODEPTR*, int, int*); // searches the tree for a particular element and returns a pointer to the node and its parent
void initTree(NODEPTR*); // initializes the tree
int max(int, int); // returns the greater of two values
int getNodeDepth(NODEPTR, int); // returns the depth of a given node in the BST
void delRoot(NODEPTR*); // deletes the root of the tree
void displayBST(NODEPTR); // displays the BST
void mirrorBST(NODEPTR*); // mirror the BST
void displayNodesAtDepth(NODEPTR, int, int); // displays all nodes at a given depth
void displayLevelOrderBST(NODEPTR); // displays the level order traversal of the BST
void delBST(NODEPTR*); // deletes a BST
void swapNodes(NODEPTR*, NODEPTR*); // swaps two nodes of the tree
void findLowestCommonAncestor(NODEPTR, int, int, NODEPTR*); // find the lowest common ancestor for two given nodes
void displayLeftViewBST(NODEPTR); // displays the left view of the BST
void getLeftNodeAtDepth(NODEPTR, int, int, int*, int*); // returns the value of the leftmost node at a given depth;
int main()
{
NODEPTR root = NULL, index = NULL, parentIndex = NULL;
initTree(&root);
int choice = 0, x = 0, y = 0, child = 0;
printf("This program implements a binary search tree with the following basic operations.\n");
do
{
printf("\n----------- MENU -------------\n");
printf("\n 1. Create a binary search tree.\n");
printf("\n 2. Insert an element into the binary search tree.\n");
printf("\n 3. Delete an element from the binary search tree.\n");
printf("\n 4. Count the nodes in the binary search tree.\n");
printf("\n 5. Count the leaf nodes in the binary search tree.\n");
printf("\n 6. Find out the height of the binary search tree.\n");
printf("\n 7. Display the inorder traversal of the binary search tree.\n");
printf("\n 8. Display the preorder traversal of the binary search tree.\n");
printf("\n 9. Display the postorder traversal of the binary search tree.\n");
printf("\n 10. Search for an element in the binary search tree.\n");
printf("\n 11. Get the depth of a node with a particular value in the binary search tree.\n");
printf("\n 12. Delete the root of the tree.\n");
printf("\n 13. Display the level order traversal of the binary search tree.\n");
printf("\n 14. Laterally invert the tree. This will break the BST properties and will require reinversion to be restored.\n");
printf("\n 15. Find the lowest common ancestor for two given nodes in the binary search tree.\n");
printf("\n 16. Display the left side view of the binary search tree.\n");
printf("\n 0. EXIT \n");
printf("\n------------------------------\n");
printf("\nPlease enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\nPlease enter the first element of the tree.\n");
scanf("%d",&x);
if(root != NULL)
{
printf("Invalid operation attempted! Tree already exists.\n");
break;
}
root = createTree(x);
printf("Element inserted. Tree created successfully.\n");
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 2: printf("Please enter the element to insert.\n");
scanf("%d",&x);
insertNodeBST(&root, x);
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 3: printf("Please enter the element to delete.\n");
scanf("%d",&x);
index = parentIndex = NULL;
child = 0;
deleteNodeBST(&root, &index, &parentIndex, x, &child); // this function is dependent on searchBST() and delRoot()
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 4: printf("The number of nodes in the tree is %d.\n", countNodeBST(root));
break;
case 5: printf("The number of leaf nodes in the tree is %d.\n", countLeafBST(root));
break;
case 6: printf("The height of the tree is %d.\n", calcHeightBST(root));
break;
case 7: if(root == NULL)
{
printf("Tree is empty!\n");
break;
}
displayInorderBST(root);
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 8: if(root == NULL)
{
printf("Tree is empty!\n");
break;
}
displayPreorderBST(root);
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 9: if(root == NULL)
{
printf("Tree is empty!\n");
break;
}
displayPostorderBST(root);
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 10: printf("Please enter the element you want to search for.\n");
scanf("%d",&x);
child = 0;
index = parentIndex = NULL;
if(searchBST(root, &index, &parentIndex, x, &child) == TRUE)
printf("Element found! Parent is %d.", parentIndex->data);
else
printf("Element not found.\n");
break;
case 11: printf("Please enter the element you want the depth of.\n");
scanf("%d",&x);
child = 0;
index = parentIndex = NULL;
if(searchBST(root, &index, &parentIndex, x, &child) == TRUE)
printf("Depth of the element is %d.", getNodeDepth(root, x));
else
printf("Element not found.\n");
break;
case 12: if(root == NULL)
{
printf("Empty tree. Operation aborted.\n");
break;
}
delRoot(&root);
printf("Root deleted successfully.\n");
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 13: displayLevelOrderBST(root);
#ifdef DEBUG
printf("\nTotal number of memory allocations: %d\n", allocCount);
#endif
break;
case 14: mirrorBST(&root);
printf("Tree mirrored successfully.\n");
break;
case 15: printf("Enter the values of the nodes for which you need the lowest common ancestor.\n");
scanf("%d", &x);
scanf("%d", &y);
NODEPTR indexX, parentIndexX, indexY, parentIndexY;
int childX = 0, childY = 0;
int foundX = searchBST(root, &indexX, &parentIndexX, x, &childX);
int foundY = searchBST(root, &indexY, &parentIndexY, y, &childY);
if(foundX == FALSE || foundY == FALSE)
{
printf("Invalid input. Operation failed. Check if the elements searched for are in the BST.\n");
break;
}
findLowestCommonAncestor(root, x, y, &index);
if(index != NULL)
printf("Lowest Common Ancestor is %d.\n", index->data);
break;
case 16: if (root == NULL)
{
printf("Tree is empty.\n");
break;
}
displayLeftViewBST(root);
break;
// case 15: displayBST(root);
// break;
case 0: delBST(&root);
printf("Thank you.\n");
break;
default: printf("\nInvalid choice. Try again.\n");
}
}while(choice != 0);
delBST(&root); // cleanup
#ifdef DEBUG
printf("\nTotal number of unreleased memory allocations: %d\n", allocCount);
#endif
return 0;
} // end
void initTree(NODEPTR* proot)
{
*proot = NULL;
}
NODEPTR createTree(int val) // creates a tree with the user input value as the root
{
NODEPTR tmp;
tmp = malloc(sizeof(struct treeNode));
if(tmp == NULL)
{
perror("Error allocating memory.\n");
exit(EXIT_FAILURE);
}
allocCount++;
tmp->data = val;
tmp->left = tmp->right = NULL;
return tmp;
}
void insertNodeBST(NODEPTR* proot, int val) // recursively inserts an element into the tree
{
if(*proot == NULL)
{
*proot = createTree(val);
printf("Element inserted successfully.\n");
return;
}
if(val < (*proot)->data)
insertNodeBST(&((*proot)->left), val);
else if(val > (*proot)->data)
insertNodeBST(&((*proot)->right), val);
else
{
printf("Operation failed! Element already exists.\n");
return;
}
}
void swapNodes(NODEPTR* pa, NODEPTR* pb)
{
NODEPTR tmp = *pb;
*pb = *pa;
*pa = tmp;
}
void mirrorBST(NODEPTR* proot)
{
if(*proot == NULL)
return;
NODEPTR parent = *proot;
swapNodes(&(parent->left), &(parent->right));
mirrorBST(&(parent->left));
mirrorBST(&(parent->right));
}
void displayLevelOrderBST(NODEPTR root)
{
int maxDepth = calcHeightBST(root);
for(int i = 0; i <= maxDepth; i++)
{
displayNodesAtDepth(root, 0, i);
printf("\n");
}
}
void displayNodesAtDepth(NODEPTR root, int currentDepth, int maxDepth)
{
if(root == NULL)
return;
if(currentDepth == maxDepth)
{
printf("%d ", root->data);
return;
}
displayNodesAtDepth(root->left, currentDepth + 1, maxDepth);
displayNodesAtDepth(root->right, currentDepth + 1, maxDepth);
}
void getLeftNodeAtDepth(NODEPTR root, int currentDepth, int maxDepth, int *isDepthVisited, int *nodeVal)
{
if(root == NULL)
return;
if(currentDepth == maxDepth && !isDepthVisited[currentDepth])
{
isDepthVisited[currentDepth] = TRUE;
*nodeVal = root->data;
return;
}
getLeftNodeAtDepth(root->left, currentDepth + 1, maxDepth, isDepthVisited, nodeVal);
getLeftNodeAtDepth(root->right, currentDepth + 1, maxDepth, isDepthVisited, nodeVal);
}
void displayLeftViewBST(NODEPTR root)
{
int val = -1;
int maxDepth = calcHeightBST(root);
int *isDepthVisited = (int*)malloc(maxDepth * sizeof(maxDepth));
allocCount++;
for (int k = 0; k < maxDepth; k++)
isDepthVisited[k] = FALSE;
for(int i = 0; i <= maxDepth; i++)
{
getLeftNodeAtDepth(root, 0, i, isDepthVisited, &val);
if (val != -1)
printf("%d ", val);
val = -1;
}
free(isDepthVisited);
allocCount--;
}
int countNodeBST(NODEPTR root) // recursively counts the number of nodes in the tree
{
if(root != NULL)
return 1 + countNodeBST(root->left) + countNodeBST(root->right);
else
return 0;
}
int getNodeDepth(NODEPTR root, int val) // recursively calculates the depth of a given node in the tree
{
if(root == NULL || (root->left == NULL && root->right == NULL))
return 0;
if(root->data == val)
return 0;
else if (val < (root->data))
return 1 + getNodeDepth(root->left, val);
else
return 1 + getNodeDepth(root->right, val);
}
void displayPreorderBST(NODEPTR root) // recursively displays the preorder traversal of the tree
{
if(root != NULL)
{
printf("%d ", root->data);
displayPreorderBST(root->left);
displayPreorderBST(root->right);
}
}
void displayPostorderBST(NODEPTR root) // recursively displays the postorder traversal of the tree
{
if(root != NULL)
{
displayPostorderBST(root->left);
displayPostorderBST(root->right);
printf("%d ", root->data);
}
}
void displayInorderBST(NODEPTR root) // recursively displays the inorder traversal of the tree
{
if(root != NULL)
{
displayInorderBST(root->left);
printf("%d ", root->data);
displayInorderBST(root->right);
}
}
int countLeafBST(NODEPTR root) // recursively counts the leaf nodes in the tree
{
if(root == NULL)
return 0;
if(root != NULL)
{
if(root->left == NULL && root->right == NULL)
return 1;
else
return countLeafBST(root->left) + countLeafBST(root->right);
}
}
int searchBST(NODEPTR root, NODEPTR* index, NODEPTR* parentIndex, int val, int* child) // recursively searches the tree for an element
{
NODEPTR tmp = root; // backs up the pointer to the root into a temporary pointer
if(root == NULL)
return FALSE;
if((root->data) == val)
{
if(*parentIndex == NULL)
*parentIndex = root;
*index = root; // returns a pointer to the found element
return TRUE;
}
if(val < (root->data))
{
if(root->left == NULL)
return FALSE;
*parentIndex = root; // backs up the pointer to the parent of the current node
root = root->left;
if((root->data) == val) // checks if the left child is the required element
{
*index = root;
root = tmp;
*child = -1; // -1 for left child
return TRUE;
}
searchBST(root, index, parentIndex, val, child);
}
else
{
if(root->right == NULL)
return FALSE;
*parentIndex = root; // backs up the pointer to the parent of the current node
root = root->right;
if((root->data) == val) // checks if the right child is the required element
{
*index = root;
root = tmp;
*child = 1; // 1 for right child
return TRUE;
}
searchBST(root, index, parentIndex, val, child);
}
}
void findLowestCommonAncestor(NODEPTR root, int x, int y, NODEPTR* lca)
{
if((x <= root->data && y >= root->data) || (y <= root->data && x >= root->data))
{
*lca = root;
return;
}
if(x < root->data && y < root->data)
findLowestCommonAncestor(root->left, x, y, lca);
if(x > root->data && y > root->data)
findLowestCommonAncestor(root->right, x, y, lca);
}
int calcHeightBST(NODEPTR root) // recursively calculates the height of the tree
{
if(root == NULL || (root->left == NULL && root->right == NULL))
return 0;
else
return max(calcHeightBST(root->left), calcHeightBST(root->right)) + 1;
}
int max(int x, int y)
{
if(x > y)
return x;
else
return y;
}
void deleteNodeBST(NODEPTR* proot, NODEPTR* index, NODEPTR* parentIndex, int val, int* child) // deletes a node with specific value
{
if(proot == NULL)
{
printf("Empty tree. Operation aborted.\n");
return;
}
if(searchBST(*proot, index, parentIndex, val, child) == FALSE) // search for the element fails
{
printf("Element not found! Operation failed.\n");
return;
}
else if((*index)->left != NULL && (*index)->right == NULL) // the node to be deleted has only left child
{
if(*child == 1)
(*parentIndex)->right = (*index)->left; // connects the right child of the parent to the left child of the node to be deleted
if(*child == -1)
(*parentIndex)->left = (*index)->left; // connects the left child of the parent to the left child of the node to be deleted
delRoot(index);
return;
}
else if((*index)->left == NULL && (*index)->right != NULL) // the node to be deleted has only right child
{
if(*child == 1)
(*parentIndex)->right = (*index)->right; // connects the right child of the parent to the left child of the node to be deleted
if(*child == -1)
(*parentIndex)->left = (*index)->right; // connects the left child of the parent to the left child of the node to be deleted
delRoot(index);
return;
}
else if((*index)->left == NULL && (*index)->right == NULL && (*parentIndex) == NULL) // the node to be deleted is the only node in the tree
{
*proot = NULL;
delRoot(index);
return;
}
else if(*index == *proot) // if the node to be deleted is the root of the tree
{
delRoot(index); // deletes the root of the tree
*proot = *index; // restores the original pointer to the root of the tree
return;
}
else
{
if((*index)->left == NULL && (*index)->right == NULL) // the node to be deleted has no children
{
if(*child == -1)
(*parentIndex)->left = NULL; // sets the left child of the parent of the element to be deleted to NULL
if(*child == 1)
(*parentIndex)->right = NULL; // sets the right child of the parent of the element to be deleted to NULL
}
if((*index)->left != NULL && (*index)->right != NULL) // the node to be deleted has both children
{
if(*child == -1)
{
delRoot(index);
(*parentIndex)->left = *index; // sets the left child of the parent to the element that has replaced the deleted element
return;
}
if(*child == 1)
{
delRoot(index);
(*parentIndex)->right = *index; // sets the right child of the parent to the element that has replaced the deleted element
return;
}
}
}
}
void delRoot(NODEPTR* proot) // deletes the root node of the tree
{
NODEPTR toDel, parent, tmp;
if((*proot)->left == NULL && (*proot)->right == NULL) // root has no child
{
free(*proot);
allocCount--;
*proot = NULL;
printf("Element deleted successfully.\n");
return;
}
if((*proot)->left != NULL && (*proot)->right == NULL) // root has only left child
{
toDel = *proot;
*proot = (*proot)->left;
free(toDel);
allocCount--;
toDel = NULL;
printf("Element deleted successfully.\n");
return;
}
if(((*proot)->right != NULL && (*proot)->left == NULL) || ((*proot)->right != NULL && (*proot)->left != NULL)) // root has only right child or both children
{
toDel = *proot; // backs up the pointer to the node to be deleted
*proot = (*proot)->right; // traverses to the right child of the node to be deleted
parent = toDel; // holds the pointer to the parent of the current node
if(((*proot)->left == NULL && (*proot)->right == NULL) || ((*proot)->left == NULL && (*proot)->right != NULL)) // the right child has no children or only has right child
{
(*proot)->left = toDel->left;
free(toDel);
allocCount--;
toDel = NULL;
printf("Element deleted successfully.\n");
return;
}
while((*proot)->left != NULL) // the right child has left child or both children
{
parent = *proot;
*proot = (*proot)->left;
}
toDel->data = (*proot)->data;
tmp = parent->left; // traverses to the left of the right child of the node to be deleted
if(tmp->left == NULL && tmp->right != NULL)
parent->left = tmp->right;
else
parent->left = NULL; // sets the left child of the parent to NULL
free(*proot);
allocCount--;
*proot = toDel;
toDel = NULL;
printf("Element deleted successfully.\n");
return;
}
}
void delBST(NODEPTR *proot)
{
if (*proot == NULL)
return;
if((*proot)->left == NULL && (*proot)->right == NULL)
{
free(*proot);
allocCount--;
*proot = NULL;
return;
}
else
{
delBST(&(*proot)->right);
delBST(&(*proot)->left);
}
}