roberts
GF Ouro
- Entrou
- Set 23, 2007
- Mensagens
- 8,173
- Gostos Recebidos
- 0
Código:
#include <stdio.h>#include <stdlib.h>
typedef struct NODO
{
int r;
struct NODO *esq;
struct NODO *dir;
} Nodo, *Arvore;
Arvore criaArvore();
Arvore insere(Arvore, int);
void preorder(Arvore);
void postorder(Arvore);
void inorder(Arvore);
int maior(Arvore);
int menor(Arvore);
void imprimeDot(Arvore);
---------------------------------------------------------
Código:
#include <stdio.h>#include <stdlib.h>
#include"exemplo.h" // usar o codigo em cima num ".h"
#define ESQ(a) a->esq
#define DIR(a) a->dir
#define RAIZ(a) a->r
#define VAZIA(a) (a == NULL)
int main()
{
int r;
Arvore arv = criaArvore();
do
{
printf("Introduza um numero (0 para sair): ");
scanf("%d", &r);
arv = insere(arv, r);
} while(r !=0);
printf("Travessia preorder: ");
preorder(arv);
printf("\nTravessia postorder: ");
postorder(arv);
printf("\nTravessia inorder: ");
inorder(arv);
printf("\nO maior e: %d ", maior(arv));
printf("\nO menor e: %d \n", menor(arv));
imprimeDot(arv);
system("pause");
return 0;
}
Arvore criaArvore()
{
return NULL;
}
Arvore insere(Arvore arv, int elemento)
{
if(VAZIA(arv))
{
arv = (Arvore)malloc(sizeof(Nodo));
RAIZ(arv) = elemento;
ESQ(arv) = NULL;
DIR(arv) = NULL;
}
else
{
if(RAIZ(arv)< elemento)
{
DIR(arv) = insere(DIR(arv), elemento);
}
else
{
ESQ(arv) = insere(ESQ(arv), elemento);
}
}
return arv;
}
void preorder(Arvore arv)
{
if(!VAZIA(arv))
{
printf("%d ", RAIZ(arv));
preorder(ESQ(arv));
preorder(DIR(arv));
}
}
void postorder(Arvore arv)
{
if(!VAZIA(arv))
{
postorder(ESQ(arv));
postorder(DIR(arv));
printf("%d ", RAIZ(arv));
}
}
void inorder(Arvore arv)
{
if(!VAZIA(arv))
{
inorder(ESQ(arv));
printf("%d ", RAIZ(arv));
inorder(DIR(arv));
}
}
int maior(Arvore arv)
{
int res=0;
if(!VAZIA(arv))
{
while(DIR(arv)!= NULL)
{
arv = DIR(arv); // arv = arv->direita;
}
res = RAIZ(arv);
}
return res;
}
int menor(Arvore arv)
{
int res=0;
if(!VAZIA(arv))
{
while(ESQ(arv)!= NULL)
{
arv = ESQ(arv); // arv = arv->esquerda;
}
res = RAIZ(arv);
}
return res;
}
void imprimeNodosDot(Arvore arv, FILE *fp)
{
if(!VAZIA(arv))
{
if (ESQ(arv)!= NULL)
{
fprintf(fp,"%d -> %d\n", RAIZ(arv), RAIZ(ESQ(arv)));
imprimeNodosDot(ESQ(arv), fp);
}
if (DIR(arv)!= NULL)
{
fprintf(fp,"%d -> %d\n", RAIZ(arv), RAIZ(DIR(arv)));
imprimeNodosDot(DIR(arv), fp);
}
}
}
void imprimeDot(Arvore arv)
{
FILE *fp = fopen("arvore.dot", "w");
fprintf(fp, "digraph Arvore {\n");
imprimeNodosDot(arv, fp);
fprintf(fp, "}\n");
fclose(fp);
//converte .dot numa imagem
system("\"C:\\Program Files (x86)\\Graphviz2.30\\bin\\dot.exe\" -Tpng arvore.dot -o arvore.png");
//abre a imagem
system("arvore.png");
}