fork(1) download
  1. #include<iostream>
  2. #include<malloc.h>
  3. using namespace std;
  4. typedef struct tree
  5. {
  6. int number;
  7. struct tree *leftChild;
  8. struct tree *rightChild;
  9.  
  10. } node;
  11. node *root=NULL;
  12.  
  13. void inorder(node *root){
  14. if(root==NULL)
  15. return;
  16.  
  17. inorder(root->leftChild);
  18.  
  19. printf("%d ", root->number);
  20.  
  21. inorder(root->rightChild);
  22. }
  23.  
  24. void insertNode(int value)
  25. {
  26. node *tempNode;
  27. node *currentNode=NULL;
  28. node *parentNode=NULL;
  29.  
  30. tempNode = (node *) malloc(sizeof(node));
  31. tempNode->number = value;
  32. tempNode->leftChild = NULL;
  33. tempNode->rightChild = NULL;
  34.  
  35. //For the very first call
  36. if(root==NULL)
  37. {
  38. root = tempNode;
  39. }
  40. else
  41. {
  42. currentNode = root;
  43. parentNode = NULL;
  44.  
  45. while(1)
  46. {
  47. parentNode = currentNode;
  48.  
  49. if(value <= parentNode->number)
  50. {
  51. currentNode = currentNode->leftChild;
  52.  
  53. if(currentNode==NULL)
  54. {
  55. parentNode->leftChild = tempNode;
  56. return;
  57. }
  58. }
  59. else
  60. {
  61. currentNode = currentNode->rightChild;
  62.  
  63. if(currentNode==NULL)
  64. {
  65. parentNode->rightChild = tempNode;
  66. return;
  67. }
  68. }
  69.  
  70. }
  71. }
  72. }
  73. int main()
  74. {
  75. int total_node;
  76. cout<<"Enter total node amount:\n";
  77. cin>>total_node;
  78. for(int i=1; i<=total_node; i++) insertNode(i);
  79. cout<<endl;
  80. inorder(root);
  81. }
  82.  
Success #stdin #stdout 0s 15224KB
stdin
Standard input is empty
stdout
Enter total node amount: