-
Notifications
You must be signed in to change notification settings - Fork 2
/
count_nodes_bst.c
136 lines (108 loc) · 2.62 KB
/
count_nodes_bst.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
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
/****************************************************************************
File name: count_nodes_bst.c
Author: babajr
*****************************************************************************/
/*
Binary Search Tree (BST).
Find the number of nodes in the tree.
Also get the sum of all the nodes in the tree.
*/
#include <stdio.h>
#include <stdlib.h>
struct BstNode
{
struct BstNode *left;
int data;
struct BstNode *right;
};
typedef struct BstNode Node;
// create global root pointer
Node *root = NULL;
/*
API to create new node.
*/
Node *getNewNode(int value)
{
// create new node.
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->left = NULL;
newNode->data = value;
newNode->right = NULL;
return newNode;
}
/*
API to insert the nodes in order to create the BST.
Recursive Insert function is used.
Assumption: BST do not contain the duplicate values, so if value
is already present, it will not be added.
*/
Node *insert(Node *ptr, int value)
{
// If BST is empty, create the new node and insert it as root node.
if(ptr == NULL)
ptr = getNewNode(value);
// If nodes are present in the tree, then check for appropriate position to
// enter the node.
else if(value < ptr->data) // If duplicate is allowed else if(value <= ptr->data)
{
ptr->left = insert(ptr->left, value);
}
else
{
ptr->right = insert(ptr->right, value);
}
return ptr;
}
/*
API to display the tree in INORDER fashion.
*/
void printInorder(Node *ptr)
{
// Tree is empty.
if(ptr == NULL)
return;
printInorder(ptr->left);
printf("%d -> ", ptr->data);
printInorder(ptr->right);
}
/*
API to count the number of nodes in the tree.
*/
int count(Node *ptr)
{
if(ptr !=NULL)
{
// count the number of nodes in left and right subtree.
// 1 is added for current node.
return (count(ptr->left) + count(ptr->right) + 1);
}
return 0;
}
/*
API to get the sum of all the elements in BST.
*/
int sumOfAllElements(Node *ptr)
{
if(ptr != NULL)
{
return (sumOfAllElements(ptr->left) +
sumOfAllElements(ptr->right) +
(ptr->data));
}
return 0;
}
int main(void)
{
root = insert(root, 30); // create the root node.
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 10);
root = insert(root, 25);
root = insert(root, 35);
printInorder(root);
printf("\n");
printf("Count of nodes in BST: %d\n", count(root));
printf("Sum of all nodes in BST: %d\n", sumOfAllElements(root));
return 0;
}