Anda di halaman 1dari 3

Definição da Estrutura de Dados

Uma árvore binária contém dois filhos: filho direito e filho esquerdo.

typedef struct tree_node tree_node, *tree;

struct tree_node {
tipo data;
tree left;
tree right;
}

typedef enum { PREORDER,INORDER,POSTORDER } ORDER;

Definições auxiliares

# define DATA(T) ((T)->data)


# define LEFT(T) ((T)->left)
# define RIGHT(T) ((T)->right)

Operações

1) Alocar um nó e inicializar o campo de dados

int allocate_tree_node (tree *p_T, tipo data) {


tree T;

T = (tree)malloc (sizeof(tree_node));
if (T==NULL)
return ERRO;
*p_T = T;
DATA(T) = data;
LEFT(T) = NULL:
RIGHT(T) = NULL;
return OK;
}

2) Liberar o espaço alocado para o nó

void free_tree_node(tree *p_T) {


free(*p_T);
*p_T=NULL:
}

3) Inicializar uma árvore vazia

int init_tree (tree *p_T) {


*p_T=NULL;
return OK;
}
4) Verificar se a árvore está vazia

int empty_tree(tree T) {
return (T==NULL) ? TRUE : FALSE;
}

5) Alocar um nó na árvore com data sendo a raiz e atribuir uma árvore à direita e outra
à esquerda

int make_root(tree *p_T, tipo data, tree right, tree left)


if (empty_tree(*p_T) == FALSE)
return ERRO;
if (allocate_tree_node(p_T,data) == ERRO)
return ERRO;
LEFT(*p_T) = left;
RIGHT(*p_T) = right;
return OK;
}

6) Destruir uma árvore

void destroy_tree(tree *p_T, void (*p_func_f)() ) {


if (empty_tree(*p_T) == FALSE) {
destroy_tree(&LEFT(*p_T),p_func_f);
if (p_func_f != NULL)
(*p_func_f)(DATA(*p_T);
free_tree_node(p_T);
}
}

7) Modos de Travessia: pré-ordem, in-ordem, pos-ordem

int traverse_tree(tree T,int (*p_func_f)(), ORDER order) {


switch (order) {
case PREORDER : return preorder_traverse(T,p_func_f);
case INORDER : return inorder_traverse(T,p_func_f);
case POSTORDER : return postorder_traverse(T,p_func_f);
}
return ERROR;
}

a) Travessia pré-ordem

int preorder_traverse (tree T,int (*p_func_f)() ) {


int rc;

if (empty_tree(T) == TRUE)
return OK;
rc = (*p_func_f)(DATA(T));
if (rc==OK)
rc = preorder_traverse(LEFT(T),p_func_f);
if (rc==OK)
rc = preorder_traverse(RIGHT(T),p_func_f);
return rc;
}
b) Travessia in-ordem

int inorder_traverse (tree T,int (*p_func_f)() ) {


int rc;

if (empty_tree(T) == TRUE)
return OK;
rc = inorder_traverse(LEFT(T),p_func_f);
if (rc==OK)
rc = (*p_func_f)(DATA(T),p_func_f);
if (rc==OK)
rc = inorder_traverse(RIGHT(T),p_func_f);
return rc;
}

c) Travessia pós-ordem

int postorder_traverse (tree T,int (*p_func_f)() ) {


int rc;

if (empty_tree(T) == TRUE)
return OK;
rc = postorder_traverse(LEFT(T),p_func_f);
if (rc==OK)
rc = inorder_traverse(RIGHT(T),p_func_f);
if (rc==OK)
rc = (*p_func_f)(DATA(T),p_func_f);
return rc;
}

Anda mungkin juga menyukai