fork download
  1. #include <iostream>
  2. using namespace std;
  3. class Node
  4. {
  5. public:
  6. Node *left,
  7. *right;
  8. int value;
  9. public:
  10. Node(void) {
  11. left = NULL;
  12. right = NULL;
  13. value = -1;
  14. }
  15. Node* getLeft() {return left;}
  16. Node* getRight() {return right;}
  17. int getValue() {return value;}
  18.  
  19. bool insert(Node** root, int val) {
  20. if (!*root) {
  21. *root = new Node();
  22. (*root)->value = val;
  23. (*root)->left = NULL; (*root)->right = NULL;
  24. }
  25. else {
  26. if (val <= (*root)->value)
  27. insert(&((*root)->left), val);
  28. else
  29. insert(&((*root)->right), val);
  30. }
  31. return true;
  32. }
  33.  
  34. int inOrder(Node *root, int x) {
  35. if (root && x > 0) {
  36. x = inOrder(root->left, x);
  37.  
  38. if (x > 0) { cout << root->value << " "; x--; }
  39.  
  40. if (root->right && x > 0)
  41. x = inOrder(root->right, x);
  42. }
  43. return x;
  44. }
  45. ~Node(void);
  46. };
  47.  
  48. int main() {
  49. Node* root = NULL;
  50. root->insert(&root, 100);
  51. root->insert(&root, 50);
  52. root->insert(&root, 150);
  53. cout << "In-Order: ";
  54. root->inOrder(root, 0);
  55. cout << endl;
  56. cout << "In-Order: ";
  57. root->inOrder(root, 1);
  58. cout << endl;
  59. cout << "In-Order: ";
  60. root->inOrder(root, 2);
  61. cout << endl;
  62. cout << "In-Order: ";
  63. root->inOrder(root, 3);
  64. cout << endl;
  65. return 0;
  66. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
In-Order: 
In-Order: 50 
In-Order: 50 100 
In-Order: 50 100 150