-
Notifications
You must be signed in to change notification settings - Fork 160
/
Statistical binary search tree.cpp
128 lines (85 loc) · 2.63 KB
/
Statistical binary search tree.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
Statistical binary search tree
*/
#include<iostream>
using namespace std;
struct NODE {
int val;
NODE* pLft;
NODE* pRgt;
int size; //the size of the subtree rooted at that node
NODE* pParent;
NODE(int n, int sz = 1) : val(n), size(sz), pLft(NULL), pRgt(NULL), pParent(NULL) {}
void setLeft(NODE* node) {
if (node==NULL) return;
pLft = node;
node->pParent = this;
}
void setRight(NODE* node) {
if (node==NULL) return;
pRgt = node;
node->pParent = this;
}
};
//O(logn) insert
void Insert(NODE* node, NODE* tmp) {
if (node == NULL|| tmp == NULL) return;
node->size++;
if (tmp->val >= node->val) {
if (node->pRgt == NULL) {
node->setRight(tmp);
} else {
Insert(node->pRgt, tmp);
}
} else {
if (node->pLft == NULL) {
node->setLeft(tmp);
} else {
Insert(node->pLft, tmp);
}
}
}
//find the n'th smallest element stored in the tree in O(logn) time
NODE *Select(NODE *root, int n) {
if (root==NULL || n <= 0) return NULL;
NODE *cur = root;
int cursum = 0;
do {
int lefttreesize = 1 + (cur->pLft == NULL ? 0 : cur->pLft->size);
int totalsum = cursum + lefttreesize;
if (totalsum == n) return curn;
if (totalsum < n) { // add the size of left subtree
cursum += lefttreesize;
}
cur = (totalsum > n ? cur->pLft : cur->pRgt); //continue to search left or right subtree
} while (cur != NULL);
return NULL;
}
//find the rank of element node in the tree in O(logn) time
int GetNum(NODE* root, NODE* node) {
if (root == NULL|| node == NULL) return 0;
if (node == root) return node->pLft == NULL ? 1 : 1 + node->pLft->size;
NODE* cur = node;
int result = 1;
while (cur->pParent != NULL) {
if (cur == cur->pParent->pRgt) { // if node is its parent right child
result += 1 + (cur->pParent->pLft == NULL ? 0 : cur->pParent->pLft->size);
}
cur = cur->pParent;
}
return result;
}
int main() {
NODE *root = new NODE(3);
Insert(root, new NODE(1));
Insert(root, new NODE(5));
NODE *p1 = new NODE(4);
Insert(root,p1);
cout<<root->size<<endl;//4
cout<<Select(root,1)->val<<endl;
cout<<Select(root,2)->val<<endl;
cout<<Select(root,3)->val<<endl;
cout<<Select(root,4)->val<<endl;
cout<<GetNum(root, p1)<<endl;
return 0;
}