/**(c) 2016 Michał (Foxbond) Chraniuk */
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef struct node {
int value;
struct node *left;
struct node *right;
}node;
node* createElem(int value);
void addElem(node *wezel, node *elem);
void printNode(node* wezel);
node *root = NULL;
int main() {
srand(time(NULL));//seed
int count;
cout << "Ile elementow? ";
cin >> count;
//tworzenie tablicy dla losowych elementow
int *tab = (int*)malloc(count*sizeof(int));
//wypelnienie tablicy
for (int i = 0;i < count;i++) {
tab[i] = rand() % 100 + 1;
}
//przepisanie tablicy do drzewa
for (int i = 0;i < count;i++) {
addElem(root, createElem(tab[i]));
}
//wyswietlenie od najw elem
printNode(root);
return 0;
}
node* createElem(int value) {
node *elem = (node*)malloc(sizeof(node));
elem->value = value;
elem->left = elem->right = NULL;
return elem;
}
void addElem(node* wezel, node* elem) {
//pierwszy elem drzewa
if (root == NULL) {
root = elem;
return;
}
//wiekszy -> prawo
if (elem->value > wezel->value) {
if (wezel->right == NULL) {
wezel->right = elem;
return;
}
else {
addElem(wezel->right, elem);
}
}
else {//mniejszy,rowny -> lewo
if (wezel->left == NULL) {
wezel->left = elem;
return;
}
else {
addElem(wezel->left, elem);
}
}
}
void printNode(node* wezel) {
if (wezel->right != NULL) {
printNode(wezel->right);
}
cout << wezel->value << endl;
if (wezel->left != NULL) {
printNode(wezel->left);
}
}
> Back