Advertisement
daniele2013

alberi binari

Jun 11th, 2013
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct tree
  5. {
  6. int x;
  7. struct tree *left;
  8. struct tree *right;
  9. };
  10.  
  11. int altezza(struct tree*);
  12. int numnodi(struct tree*);
  13. struct tree *insabr(struct tree*,int);
  14.  
  15. int main()
  16. {
  17. struct tree *root=NULL;
  18. printf("%d %d", altezza(root), numnodi(root));
  19. return 0;
  20. }
  21.  
  22. int altezza(struct tree *root)
  23. {
  24. int h1, h2;
  25. if(root==NULL)
  26. return -1;
  27. h1=altezza(root->left);
  28. h2=altezza(root->right);
  29. if(h1>h2)
  30. return h1+1;
  31. else
  32. return h2+1;
  33. }
  34.  
  35. int numnodi(struct tree *root)
  36. {
  37. int res=0, s1, s2;
  38. if(root!=NULL)
  39. {
  40. s1=numnodi(root->left);
  41. s2=numnodi(root->right);
  42. res=s1+s2+1;
  43. }
  44. return res;
  45. }
  46.  
  47. struct tree *insabr(struct tree *root, int k)
  48. {
  49. if(root==NULL)
  50. {
  51. root=(struct tree*)malloc(sizeof(struct tree));
  52. root->x=k;
  53. root->left=NULL;
  54. root->right=NULL;
  55. }
  56. else
  57. {
  58. if(k<root->x)
  59. root->left=insabr(root->left,k);
  60. else
  61. root->right=insabr(root->right,k);
  62. }
  63. return root;
  64. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement