[Geeks for Geeks] Count BST nodes that lie in a given range

Count BST nodes that lie in a given range

Given a Binary Search Tree (BST) and a range l-h(inclusive), count the number of nodes in the BST that lie in the given range.

  • The values smaller than root go to the left side
  • The values greater and equal to the root go to the right side
  • Time : O(n)
  • Space : O(d)
1
2
3
4
5
6
7
8
9
10
11
12
13
int getCount(Node *root, int l, int h) {
if(!root) return 0;
int res = 0;
if(l <= root->data and root->data <= h) {
res = 1 + getCount(root->left, l, h) + getCount(root->right, l, h);
} else if(l > root->data) {
res = getCount(root->right, l, h);
} else {
res = getCount(root->left, l, h);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/count-bst-nodes-that-lie-in-a-given-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.