10. előadás
Bináris rendező fa

- Vesszük az első elemet: ez a gyökér
- Ha a kövi kisebb => balra írjuk
- Ha a kövi nagyobb => jobbra írjuk
- Rekurzívan megyünk, amíg el tudjuk helyezni
Implementálás C-ben
A számokat a standard inputról olvassuk be
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int value;
struct Node *left; // bal ág pointere
struct Node *right; // jobb ág pointere
};
typedef struct Node node_t;
void print(node_t *root)
{
//if( root ) // ugyan az, mint a követező sor
if( NULL != root ) //Yoda pillanat
{
//print((*root).left); // ez is ugyan az, mint a követező sor
print(root->left); // Bal oldali (kisebb) elemek kiírása
printf("%d ", root->value);
print(root->right); // Jobb oldali (nagyobb) elemek kiírása
}
}
void insert(node_t **proot, int val)
{
if ((*proot) != NULL)
{
node_t *root = *proot;
if(val < root->value)
{
// `value` kisebb, mint `root`, úgyhogy a bal oldalra megy
insert(&root->left, val);
}
else
{
// `value` nagyobb, mint `root`, úgyhogy a jobb oldalra megy
insert(&root->right, val);
}
}
else
{
// Még nincs (*proot) elem, úgyhogy allokálunk hozzá egy Node-ot
*proot = (node_t *)malloc( sizeof(node_t) );
if( NULL == *proot )
{
// Nem lehetett allokálni.
fprintf(stderr, "Out of memory\n");
exit(1);
}
node_t *root = *proot;
root->left = NULL;
root->right = NULL;
root->value = val;
}
}
void delete(node_t *root)
{
if( NULL != root )
{
delete(root->left);
delete(root->right);
free(root);
}
}
int main()
{
int i;
// első elemre mutató pointer
node_t *head = NULL;
//`scanf` visszaadja a beszkennelt elemek számát
while ( 1 == scanf("%d", &i) )
{
insert(&head, i);
}
print(head);
delete(head);
return 0;
}
Random szám generálás
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("argc == %d\n", argc);
for( int i = 0; i < argc; ++i )
{
printf("argv[%d] == %s\n", i, argv[i]);
// > gcc -Wall -Wextra --pedantic main.c
// > ./a.out a b asd
//
// argc == 4
// argv[0] == ./a.out
// argv[1] == a
// argv[2] == b
// argv[3] == asd
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int max = 1000;
if( argc > 1 )
{
//atoi: string -> int konverzió
int max2 = atoi(argv[1]);
max = (0 == max2) ? max : max2; //ternary operator -> sorbeli `if`
}
for( int i = 0; i < max; ++i )
{
printf("%d ", rand());
}
return 0;
}