matheus__serpa

arvore

May 26th, 2020
1,560
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct _Nodo{
  6.     char nome[101];
  7.     float nota_P1;
  8.     struct _Nodo *esq, *dir;
  9. }Nodo;
  10.  
  11. void cria_arvore(Nodo **arvore){
  12.     *arvore = NULL;
  13. };
  14.  
  15. /* Retorna 1 se foi possivel inserir. Caso contrario 0. */
  16. int insere_raiz(Nodo **arvore, char *nome_aluno, float nota){
  17.     if(*arvore == NULL){
  18.  
  19.         Nodo *novo = (Nodo *) malloc(sizeof(Nodo));
  20.        
  21.         strcpy(novo->nome, nome_aluno);
  22.         novo->nota_P1 = nota;
  23.         novo->esq = novo->dir = NULL;
  24.  
  25.         *arvore = novo;
  26.  
  27.         return 1;
  28.     }
  29.     return 0;
  30. }
  31.  
  32. int insere_dir(Nodo **arvore, char *pai, char *nome_aluno, float nota){
  33.     if(*arvore == NULL)
  34.         return 0;
  35.     else if(strcmp((*arvore)->nome, pai) == 0){
  36.         if((*arvore)->dir == NULL){
  37.             Nodo *novo = (Nodo *) malloc(sizeof(Nodo));
  38.            
  39.             strcpy(novo->nome, nome_aluno);
  40.             novo->nota_P1 = nota;
  41.             novo->esq = novo->dir = NULL;
  42.  
  43.             (*arvore)->dir = novo;     
  44.             return 1;
  45.         }else
  46.             return 0;
  47.     }
  48.     return insere_dir(&(*arvore)->esq, pai, nome_aluno, nota) || insere_dir(&(*arvore)->dir, pai, nome_aluno, nota);
  49. }
  50.  
  51. int main(){
  52.     Nodo *arvore;
  53.  
  54.     cria_arvore(&arvore);
  55.  
  56.     if(insere_raiz(&arvore, "Matheus", 6.5) == 1)
  57.         printf("Inserido com sucesso!\n");
  58.     else
  59.         printf("Erro: árvore ja possui raiz!\n");
  60.  
  61.     if(insere_dir(&arvore, "Matheus", "João", 9.5) == 1)
  62.         printf("Inserido com sucesso!\n");
  63.     else
  64.         printf("Erro: árvore ja possui raiz!\n");
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment