-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path34_DeleteLeafNodes_binarySearchTree.c
99 lines (85 loc) · 2.19 KB
/
34_DeleteLeafNodes_binarySearchTree.c
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
// Program to count and delete the leaf nodes in a Binary Search Tree
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *left;
struct Node *right;
};
int countLeafNodes(struct Node *root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 1;
return countLeafNodes(root->left) + countLeafNodes(root->right);
}
struct Node *removeLeafNodes(struct Node *root)
{
if (root == NULL)
return root;
if (root->left == NULL && root->right == NULL)
{
free(root);
return NULL;
}
root->left = removeLeafNodes(root->left);
root->right = removeLeafNodes(root->right);
return root;
}
struct Node *insertIntoTree(struct Node *, int);
void displayInorder(struct Node *);
int main()
{
struct Node *root = NULL;
root = insertIntoTree(root, 24);
root = insertIntoTree(root, 41);
root = insertIntoTree(root, 16);
root = insertIntoTree(root, 31);
root = insertIntoTree(root, 23);
root = insertIntoTree(root, 65);
root - insertIntoTree(root, 5);
printf("\nBinary Search Tree Inorder\n");
displayInorder(root);
int count = countLeafNodes(root);
printf("\nNumber of leaf nodes: %d", count);
removeLeafNodes(root);
printf("\nBinary Search Tree Inorder After removing leaf nodes\n");
displayInorder(root);
}
struct Node *insertIntoTree(struct Node *root, int data)
{
struct Node *curr = root, *parent = NULL;
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
if (root == NULL)
return newNode;
while (curr)
{
parent = curr;
if (data <= curr->data)
{
curr = curr->left;
if (curr == NULL)
parent->left = newNode;
}
else
{
curr = curr->right;
if (curr == NULL)
parent->right = newNode;
}
}
return root;
}
void displayInorder(struct Node *root)
{
if (root == NULL)
return;
displayInorder(root->left);
printf("%d ", root->data);
displayInorder(root->right);
}