/**(c) 2016 Michał (Foxbond) Chraniuk */
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <iostream>
#include <conio.h>
using namespace std;
//element drzewa
typedef struct elem {
char name[50];
int age;
struct elem *left;
struct elem *right;
}elem;
//korzen
elem *root = NULL;
void cls() {
system("cls");
}
void addPerson();
void printTree();
void printNode(elem* node);
//utowrzenie węzła
elem* createElem(string name, int age) {
elem* osoba = (elem*)malloc(sizeof(elem));
strcpy(osoba->name, name.c_str());
osoba->age = age;
osoba->left = NULL;
osoba->right = NULL;
return osoba;
}
//sprawdzanie priorytetu
int compareElem(elem* first, elem* second) {
//w tym wypadku na podstawie wieku, starszy ma wyższy priorytet
if (first->age <= second->age) {
return 1;
}
return 0;
}
//dodanie elementu do drzewa
void addElem(elem* node, elem* osoba) {
if (root == NULL) {//pierwszy element jako korzeń
root = osoba;
return;
}
//wyliczenie priorytetu
if (compareElem(node, osoba) == 1) {//wyższy priorytet prawo
if (node->right == NULL) {
node->right = osoba;
return;
}
addElem(node->right, osoba);
}
else {//niższy priorytet lewo
if (node->left == NULL) {
node->left = osoba;
return;
}
addElem(node->left, osoba);
}
}
int main() {
char opt;
do {
cls();
cout << "1. Dodaj osobe\n2. Wyswietl\n0. Wyjscie\n";
opt = _getch();
if (opt == '1') {
addPerson();
}
else if (opt == '2') {
printTree();
}
} while (opt != '0');
return 0;
}
//dodanie osoby
void addPerson() {
string imie;
int wiek;
cls();
cout << "Podaj imie: ";
cin >> imie;
cout << "\nPodaj wiek: ";
cin >> wiek;
addElem(root, createElem(imie, wiek));
}
//wyswietlenie drzewa
void printTree() {
cls();
if (root == NULL) {
cout << "Drzewo jest puste!";
_getch();
return;
}
cout << "Wiek\tImie\n";
printNode(root);
_getch();
}
//wyswietlenie węzła i rekurencyjnie potomków
void printNode(elem* node) {
if (node == NULL) {
return;
}
if (node->right != NULL) {
printNode(node->right);
}
cout << node->age << "\t" << node->name << "\n";
if (node->left != NULL) {
printNode(node->left);
}
}
> Back