-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search_Tree.cpp
85 lines (84 loc) · 1.98 KB
/
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
#include<iostream>
typedef long long ll;
struct Node
{
Node *Left,*Right;
ll data;
int counter;
};
class Tree
{
public:
Node *root = nullptr;
Node *Find(Node *p, ll x)
{
if(p == nullptr || p->data == x)
return p;
if(x < p->data)
return Find(p->Left,x);
else if(x > p->data)
return Find(p->Right,x);
}
void Insert(ll x)
{
if(this->root == nullptr)
root = new Node {nullptr,nullptr,x,1};
else
{
Node *p = root;
while(true)
{
if(p->data == x)
{
p->counter++;
return;
}
else if(p->data > x)
{
if(p->Left != nullptr)
p = p->Left;
else
{
Node *NewN = new Node {nullptr,nullptr,x,1};
p->Left = NewN;
return;
}
}
else if(p->data < x)
{
if(p->Right != nullptr)
p=p->Right;
else
{
Node *NewN = new Node {nullptr,nullptr,x,1};
p->Right = NewN;
return;
}
}
}
}
}
};
int main()
{// ios_base::sync_with_stdio(0);std::cin.tie(0);
int N_oper;
ll x;
char Oper_char;
Tree A;
std::cin >> N_oper;
while(N_oper--)
{
std::cin >> Oper_char >> x;
if(Oper_char == 'P')
{
Node *aux = A.Find(A.root,x);
if(aux != nullptr)
std::cout << aux->counter << "\n";
else
std::cout << "0\n";
}
else if(Oper_char == 'A')
A.Insert(x);
}
return 0;
}