forked from adarshpandey10t/Hacktoberfestmine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount_BST_nodes_that_lie_in_a_given_range.cpp
More file actions
84 lines (69 loc) · 1.54 KB
/
Count_BST_nodes_that_lie_in_a_given_range.cpp
File metadata and controls
84 lines (69 loc) · 1.54 KB
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
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* right;
Node* left;
Node(int x) {
data = x;
right = NULL;
left = NULL;
}
};
Node *insert(Node *root, int data)
{
if (root == NULL)
root = new Node(data);
else if (data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}
/*
structure of a BST node:
*/
struct Node {
int data;
Node* right;
Node* left;
Node(int x) {
data = x;
right = NULL;
left = NULL;
}
};
int getCountOfNode(Node *root, int l, int h)
{
if (root == NULL)
return 0;
if (root->data == l && root->data == h)
return 1;
if (root->data <= h && root->data >= l)
return 1 + getCountOfNode(root->left, l, h) + getCountOfNode(root->right, l, h);
else if (root->data < l)
return getCountOfNode(root->right, l, h);
else if (root->data > h)
return getCountOfNode(root->left, l, h);
}
int main() {
int t;
cin >> t;
while (t--)
{
Node *root = NULL;
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
for (int i = 0; i < n; i++)
{
root = insert(root, arr[i]);
}
int l, h;
cin >> l >> h;
cout << getCountOfNode(root, l, h) << endl;
}
return 0;
}