This commit is contained in:
Aelita4 2022-06-04 21:31:07 +02:00
parent 3477772b72
commit 2a8d28967f
Signed by: Aelita4
GPG Key ID: E4773B4E7238A472
2 changed files with 81 additions and 9 deletions

View File

@ -5,6 +5,7 @@ using namespace std;
BST::BST():root(NULL) {}
BST::BST(int tab[], int size) {
root = NULL; // 5 linijka nie chce sie u mnie wykonac z jakiegos powodu, dlatego dorzucam to
for (int i = 0; i < size; i++)
insert(root, tab[i]);
}
@ -26,21 +27,81 @@ bool BST::insert(BSTNode*& node, int wartosc) {
return false;
}
//BSTNode* BST::search(int key) {}
BSTNode* BST::search(int key) {
return search(root, key);
}
//BSTNode* BST::search(BSTNode* node, int key) {}
BSTNode* BST::search(BSTNode* node, int key) {
BSTNode* p = NULL;
//int BST::minKey() {}
BSTNode* tmp = node;
while(tmp != NULL) {
if(tmp->data == key) {
p = tmp;
break;
} else {
if(tmp->data > key) tmp = tmp->left;
else tmp = tmp->right;
}
}
//int BST::minKey(BSTNode* node) {}
return p;
}
//int BST::maxKey() {}
int BST::minKey() {
return minKey(root);
}
//void BST::inorder(BSTNode* x) {}
int BST::minKey(BSTNode* node) {
BSTNode* tmp = node;
//void BST::preorder(BSTNode* x) {}
int minn = tmp->data;
//void BST::postorder(BSTNode* x) {}
while(tmp != NULL) {
if(tmp->left != NULL) {
tmp = tmp->left;
minn = tmp->data;
} else {
break;
}
}
return minn;
}
int BST::maxKey() {
int maxx = BST::root->data;
BSTNode* tmp = BST::root;
while(tmp != NULL) {
if(tmp->right != NULL) {
tmp = tmp->right;
maxx = tmp->data;
} else {
break;
}
}
return maxx;
}
void BST::inorder(BSTNode* x) {
if(x->left != NULL) inorder(x->left);
cout << x->data << " ";
if(x->right != NULL) inorder(x->right);
}
void BST::preorder(BSTNode* x) {
cout << x->data << " ";
if(x->left != NULL) preorder(x->left);
if(x->right != NULL) preorder(x->right);
}
void BST::postorder(BSTNode* x) {
if(x->left != NULL) postorder(x->left);
if(x->right != NULL) postorder(x->right);
cout << x->data << " ";
}
void BST::print(BSTNode* x){
if (!x->left && !x->right) return;

View File

@ -5,7 +5,18 @@ using namespace std;
int main()
{
int dane[]{ 8, 3, 6, 1, 7, 10, 0, 2, 11, 4, 9 }; //{ 10,6,15,1,8,12,16,0,2,7,9 };
BST drzewo(dane, size(dane));
BST drzewo(dane, sizeof(dane) / sizeof(int)); // size() wywalalo mi blad deklaracji, zastapilem to czyms takim, "That works too."
cout << "Search for 10: " << drzewo.search(10) << endl;
cout << "Search for 42: " << drzewo.search(42) << endl;
cout << "Min: " << drzewo.minKey() << endl;
cout << "Max: " << drzewo.maxKey() << endl;
cout << "Inorder: "; drzewo.inorder(drzewo.root); cout << endl;
cout << "Preorder: "; drzewo.preorder(drzewo.root); cout << endl;
cout << "Postorder: "; drzewo.postorder(drzewo.root); cout << endl;
drzewo.print(drzewo.root);
cout << endl;