-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCount_nodes_that_lie_in_given_range.cpp
65 lines (56 loc) · 1.42 KB
/
Count_nodes_that_lie_in_given_range.cpp
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
/*
Problem Statement:
-----------------
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.
Example 1:
---------
Input:
10
/ \
5 50
/ / \
1 40 100
l = 5, h = 45
Output: 3
Explanation: 5 10 40 are the node in the range.
Example 2:
---------
Input:
5
/ \
4 6
/ \
3 7
l = 2, h = 8
Output: 5
Explanation: All the nodes are in the given range.
Your Task: This is a function problem. You don't have to take input. You are required to complete the function getCountOfNode()
that takes root, l ,h as parameters and returns the count.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(Height of the BST).
*/
// Link --> https://practice.geeksforgeeks.org/problems/count-bst-nodes-that-lie-in-a-given-range/1#
// Code:
int counter = 0;
void inorder(Node *root , int l , int h)
{
if(root == NULL)
return;
if(root->data >= l and root->data <= h)
{
counter++;
inorder(root->left , l , h);
inorder(root->right , l , h);
}
else if(root->data < l)
inorder(root->right , l , h);
else
inorder(root->left , l , h);
}
int getCount(Node *root , int l , int h)
{
counter = 0;
inorder(root , l , h);
return counter;
}