Arbori P 1
Arbori P 1
Arbori P 1
1. Noiunea de arbore
2. Arbori oarecare
3. Arbori binari
4. Crearea si parcurgerea unui arbore binar
5. Arbori binari de cautare
6. Arbori binari echilibrati
7. Arbori optimi
8. Arbori orecare
ntroducere
Nivel 0
A
Nivel 1
B C
Nivel 2
D E F G
Nivel 3
H I J
Arbore binar ordonat
struct tnode
{ tip inf;
struct tnode *left;
struct tnode *right;
};
Parcurgerea in inordine
(stanga varf dreapta SVD)
Parcurgerea in preordine
(varf - stanga dreapta VSD)
Parcurgerea in postordine
(stanga dreapta varf SDV)
Solutia este: 2, 1 ,6 , 4, 3, 7, 5
Parcurgerea n postordine a arborelui binar
Solutia este: 2, 6, 4, 7, 5, 3, 1
Solutiile de parcurgere a arborelui prezentat sunt:
E x e m p l u 1 . S e v a e l a b o r a u n p rog r a m p e n t r u
i m p l e m e n t a re i p a rcu r g e re u n u i a r b o re b i n a r
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
struct Node
{ int d;
Node *left;
Node *right;
};
// Crearea primului nod
Node * first(int d);
// Inserarea inui nod nou
Node * search_insert(Node *root, int d);
// Parcurgerea arbotrelui
void print_tree(Node *root, int l);
Ex.1. Continuare
int main()
{ int b[] = {10, 25, 20, 6, 21, 8, 1, 30};
//Declarm i iniializm pointerul root
Node *root = first(b[0]);
//Inserm noduri n arbore
for (int i=1; i<8; i++) search_insert(root , b[i]);
clrscr();
// Afisam arbore
print_tree(root , 0);
getch();
return 0;
}
Ex.1. Continuare
struct nod
{ int inf;
int dim;
struct nod* tab[100];
};
struct nod * crearb();
/* Functia pentru parcurgerea in adincime */
void padinc(struct nod *);
/*Functia pentru parcurgerea in latime*/
void plat(struct nod *);
Exemplu
int main()
{ struct nod *root;
clrscr();
/*Creez arborele*/
root = crearb();
printf("Parcurgere in adincime:");
padinc(root);
printf("\nParcurgere in latime:");
plat(root);
return 0;
}
Exemplu
struct nod * crearb()
{
int inf, n, i;
struct nod *p;
printf("Inf=");
scanf("%d", &inf);
p = malloc( sizeof(struct nod) );
p->inf = inf;
printf("Cati fii are?");
scanf("%d", &n);
p->dim = n;
for(i = 0; i < n; i++)
p->tab[i] = crearb();
return p;
}
Exemplu
void padinc(struct nod *p)
{
int i;
if( p != NULL )
{
printf("%d", p->inf);
for( i = 0; i < p->dim; i++)
padinc( p->tab[i] );
}
}
Exemplu
void plat(struct nod *p)
{ struct nod *queue[100];
struct nod *t; int front = 0, back = 0;
int i;
queue[ front++ ] = p;
while ( ! (front == back) )
{
t = queue[ back ]; back++;
printf("%d", t->inf);
for(i = 0; i < t->dim; i++)
queue[ front++ ] = t->tab[i];
}
}
ARBORI BINARI