Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. /*this program builds a binary tree*/
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. /*external variables*/
  6. struct node{
  7. int data;
  8. struct node* left;
  9. struct node* right;
  10. };
  11. struct node* root = NULL;
  12.  
  13. /*prototypes*/
  14. struct node* constructor(int number);
  15. struct node* addNode(int number, struct node* current);
  16.  
  17. /*main*/
  18. /*since there isn't a real tree or any data, main looks a bit skant*/
  19. /*but the other functions are what really matter here*/
  20. int main(int argc, char *argv[])
  21. {
  22. int number = 0;
  23.  
  24. if (argc == 2)
  25. {
  26. number = atoi(argv[1]);
  27. }
  28.  
  29. addNode(number, root);
  30.  
  31. return 0;
  32. }
  33.  
  34. /*makes a new node, or sets the root if it's the first*/
  35. struct node* constructor(int number)
  36. {
  37. struct node* newNode = (struct node*)malloc(sizeof(struct node));
  38. if (newNode == NULL)
  39. {
  40. printf("Error allocating new node!\n");
  41. return NULL;
  42. }
  43.  
  44. newNode->data = number;
  45. newNode->left = NULL;
  46. newNode->left = NULL;
  47.  
  48. if (root == NULL)
  49. {
  50. root = newNode;
  51. }
  52.  
  53. return newNode;
  54. }
  55.  
  56. struct node* addNode(int number, struct node* current)
  57. {
  58. /*if we're at the end of a branch*/
  59. if (current == NULL)
  60. {
  61. constructor(number);
  62. }
  63.  
  64. /*if we need to go down branches further*/
  65. if (number < current->data)
  66. {
  67. addNode(number, current->left);
  68. }
  69. else if (number > current->data)
  70. {
  71. addNode(number, current->right);
  72. }
  73. else
  74. {
  75. printf("dickbutt");
  76. }
  77.  
  78. return current;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement