Guest User

Untitled

a guest
May 24th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. using namespace std;
  4.  
  5. struct node {
  6. int value;
  7. node * left;
  8. node * right;
  9. bool deleted;
  10. };
  11.  
  12. void insert(node *parent, int value);
  13. void preorderTraverse(node *ptr);
  14.  
  15. void insert(node *parent, int value)
  16. {
  17.  
  18. if (!parent->value)
  19. {
  20. parent->value = value;
  21. return;
  22. }
  23.  
  24. /*
  25. node *child;
  26. if (parent->value > value) //Child needs to be a reference not a copy
  27. child = parent->left; //This compiles (a copy)
  28. else
  29. child = &parent->right; //This doesn't (attempt at pointer)
  30.  
  31. if (child == NULL)
  32. {
  33. child = new node();
  34. child->value = value;
  35. return;
  36. }
  37.  
  38. insert(child, value);
  39. */
  40.  
  41. if (parent->value > value)
  42. {
  43. if (parent->left == NULL)
  44. {
  45. parent->left = new node();
  46. parent->left->value = value;
  47. return;
  48. }
  49. insert(parent->left, value);
  50. } else
  51. {
  52. if (parent->right == NULL)
  53. {
  54. parent->right = new node();
  55. parent->right->value = value;
  56. return;
  57. }
  58. insert(parent->right, value);
  59. }
  60. };
  61.  
  62. void preorderTraverse(node *ptr)
  63. {
  64. if (ptr != NULL)
  65. {
  66. printf("\nValue = %d", ptr->value);
  67. preorderTraverse(ptr->left);
  68. preorderTraverse(ptr->right);
  69. }
  70. };
  71.  
  72. int main (int argc, char * const argv[]) {
  73.  
  74. node * tree = new node();
  75.  
  76. for (int x = 0; x < 100; x++)
  77. insert(tree, rand());
  78.  
  79. preorderTraverse(tree);
  80.  
  81. return 0;
  82. }
Add Comment
Please, Sign In to add comment