Skip to content

Commit bfe9266

Browse files
committed
Added height and diameter functions and fixed the countNodes function
1 parent f36c3dd commit bfe9266

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

BST/bst.cpp

+26-2
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,23 @@ int countNodes(struct node * root){
9191
if(root==NULL)
9292
return 0;
9393
else
94-
return 1+ count(root->left) + count(root->right);
94+
return 1 + countNodes(root->left) + countNodes(root->right);
95+
}
96+
97+
98+
//This function calclulates the height of the binary search tree.
99+
int height(struct node *root){
100+
if(root==NULL)
101+
return 0;
102+
return 1 + max(height(root->left),height(root->right));
103+
}
104+
105+
106+
//This function calculates the diameter of the binary search tree.
107+
int diameter(struct node *root){
108+
if(root == NULL)
109+
return 0;
110+
return max(1 + height(root->left) + height(root->right), max(diameter(root->left),diameter(root->right)));
95111
}
96112

97113
int main() {
@@ -108,15 +124,23 @@ int main() {
108124
create(bst, 12);
109125
create(bst, 21);
110126
// Inorder permutate from left -> root -> right
127+
cout << "The Inorder traversal of the tree is : ";
111128
inorder(bst);
112129
cout << endl;
113130
// Postorder permutate from left -> right -> root
131+
cout << "The Postorder traversal of the tree is : ";
114132
postorder(bst);
115133
cout << endl;
116134
// Preorder permutate from root -> left -> right
135+
cout << "The Preorder traversal of the tree is : ";
117136
preorder(bst);
118137
cout << endl;
119138
// Count total number of nodes in the tree
120-
cout << countNodes(root);
139+
cout << "The number of nodes in the tree : ";
140+
cout << countNodes(bst) << endl;
141+
cout << "The height of the tree is : ";
142+
cout << height(bst) << endl;
143+
cout << "The diameter of the tree is : ";
144+
cout << diameter(bst) << endl;
121145
return 0;
122146
}

0 commit comments

Comments
 (0)