Advertisement
argentinapb

Untitled

Jun 17th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct arvore{
  5. int elemento;
  6. struct arvore *dir;
  7. struct arvore*esq;
  8. };
  9. typedef struct arvore arvore;
  10.  
  11. arvore *aloca (int x)
  12. {
  13. arvore *novo = (arvore*) malloc(sizeof(arvore));
  14. novo->dir = NULL;
  15. novo->esq = NULL;
  16. novo->elemento = x;
  17.  
  18. return novo;
  19. }
  20.  
  21. void inserir(arvore *p, int x)
  22. {
  23. if(x > p->elemento)
  24. {
  25. if(p->dir == NULL)
  26. {
  27. p->dir = aloca(x);
  28. }
  29. else
  30. {
  31. inserir(p->dir,x);
  32. }
  33. }
  34. else if( x < p->elemento)
  35. {
  36. if(p->esq == NULL)
  37. {
  38. p->esq = aloca(x);
  39. }
  40. else
  41. {
  42. inserir(p->esq, x);
  43. }
  44. }
  45. }
  46.  
  47. void mostrar_em_ordem(arvore *p)
  48. {
  49. if(p == NULL)
  50. {
  51. return;
  52. }
  53. mostrar_em_ordem(p->esq);
  54. printf("%d ",p->elemento);
  55. mostrar_em_ordem(p->dir);
  56. }
  57.  
  58. int main()
  59. {
  60. arvore arv1;
  61. arv1.dir = NULL;
  62. arv1.esq = NULL;
  63.  
  64. printf("Digite a raiz da arvore: ");
  65. scanf("%d",&arv1.elemento);
  66.  
  67. inserir(&arv1,3);
  68. inserir(&arv1,1);
  69. inserir(&arv1,8);
  70. inserir(&arv1,2);
  71. inserir(&arv1,4);
  72. inserir(&arv1,0);
  73.  
  74. mostrar_em_ordem(&arv1);
  75.  
  76. return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement