Advertisement
Guest User

Untitled

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