Advertisement
CarlosWGama

Estrutura Arvore e Inserir

Oct 9th, 2018
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.01 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct arvore {
  5.     struct no *raiz;
  6. };
  7.  
  8. struct no {
  9.     struct no *esq;
  10.     int valor;
  11.     struct no *dir;
  12. };
  13.  
  14.  
  15. struct no* inserir(struct no *noAtual, int valor) {
  16.  
  17.     if (noAtual == NULL) {
  18.         struct  no *novoNo = malloc(sizeof(struct no));
  19.         novoNo->valor = valor;
  20.         novoNo->esq = NULL;
  21.         novoNo->dir = NULL;
  22.         return novoNo;
  23.     } else {
  24.         //Decidir o que se vou para esquerda ou direita
  25.         if (valor < noAtual->valor)
  26.             noAtual->esq = inserir(noAtual->esq, valor);
  27.         else
  28.             noAtual->dir = inserir(noAtual->dir, valor);
  29.     }
  30. }
  31.  
  32.  
  33.  
  34. int main() {
  35.     struct arvore *arvore = malloc(sizeof(struct arvore));
  36.     arvore->raiz = NULL;
  37.  
  38.     arvore->raiz = inserir(arvore->raiz, 10);
  39.     arvore->raiz = inserir(arvore->raiz, 7);
  40.     arvore->raiz = inserir(arvore->raiz, 15);
  41.     arvore->raiz = inserir(arvore->raiz, 14);
  42.  
  43.  
  44.     printf("%d", arvore->raiz->dir->esq->valor);
  45.  
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement