-
Notifications
You must be signed in to change notification settings - Fork 31
/
Rank of an element in a streamusing linked list.cpp
87 lines (74 loc) · 1.48 KB
/
Rank of an element in a streamusing linked list.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// CPP program to find rank of an
// element in a stream.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
int leftSize;
};
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
temp->leftSize = 0;
return temp;
}
// Inserting a new Node.
Node* insert(Node*& root, int data)
{
if (!root)
return newNode(data);
// Updating size of left subtree.
if (data <= root->data) {
root->left = insert(root->left, data);
root->leftSize++;
}
else
root->right = insert(root->right, data);
return root;
}
// Function to get Rank of a Node x.
int getRank(Node* root, int x)
{
// Step 1.
if (root->data == x)
return root->leftSize;
// Step 2.
if (x < root->data) {
if (!root->left)
return -1;
else
return getRank(root->left, x);
}
// Step 3.
else {
if (!root->right)
return -1;
else {
int rightSize = getRank(root->right, x);
if(rightSize == -1 ) return -1;
return root->leftSize + 1 + rightSize;
}
}
}
// Driver code
int main()
{
int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 4;
Node* root = NULL;
for (int i = 0; i < n; i++)
root = insert(root, arr[i]);
cout << "Rank of " << x << " in stream is: "
<< getRank(root, x) << endl;
x = 13;
cout << "Rank of " << x << " in stream is: "
<< getRank(root, x) << endl;
x = 8;
cout << "Rank of " << x << " in stream is: "
<< getRank(root, x) << endl;
return 0;
}