-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19-10.cpp
125 lines (121 loc) · 2.07 KB
/
19-10.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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* par, *left, *right;
Node(int data) {
this->data = data;
par = left = right = NULL;
}
void setLeft(Node* node) {
if (node == NULL) {
this->left = NULL;
}
else {
this->left = node;
node->par = this;
}
}
void setRight(Node* node) {
if (node == NULL) {
this->right = NULL;
}
else {
this->right = node;
node->par = this;
}
}
};
class BST {
public:
Node* root;
BST() {
root = NULL;
}
Node* find(int data) {
Node* cur = root;
while (cur != NULL) {
if (data == cur->data) {
return cur;
}
else if (data > cur->data) {
cur = cur->right;
}
else {
cur = cur->left;
}
}
return cur;
}
void insert(int data) {
Node* node = new Node(data);
if (root == NULL) {
root = node;
return;
}
Node* par = NULL;
Node* cur = root;
while (cur != NULL) {
par = cur;
if (data > cur->data) {
cur = cur->right;
}
else {
cur = cur->left;
}
}
if (data > par->data) {
par->setRight(node);
}
else {
par->setLeft(node);
}
}
void remove(int data) {
Node* node = find(data);
Node* par = node->par;
if (node->left == NULL && node->right == NULL) {
par->left == node ? par->left = NULL : par->right = NULL;
}
else if (node->left == NULL || node->right == NULL) {
Node* child = node->left == NULL ? node->right : node->left;
child->par = par;
if (node == root) {
root = child;
return;
}
par->left == node ? par->left = child : par->right = child;
}
else {
Node* cur = node->right;
while (cur->left != NULL) {
cur = cur->left;
}
int temp = cur->data;
remove(cur->data);
node->data = temp;
}
}
int height(Node* node) {
if (node == NULL) {
return 0;
}
int left = height(node->left);
int right = height(node->right);
return 1 + (left > right ? left : right);
}
};
int main() {
int t, n, temp;
cin >> t;
while (t--) {
BST b;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> temp;
b.insert(temp);
}
cout << b.height(b.root) - 1 << endl;
}
}