fork download
  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;
  4.  
  5. class node
  6. {
  7. int data;
  8. int no_of_children;
  9. node* left;
  10. node* right;
  11.  
  12. public:
  13. void set_data(int a)
  14. {
  15. data=a;
  16. }
  17.  
  18. int get_data()
  19. {
  20. return data;
  21. }
  22.  
  23. void set_left_node(node* anode)
  24. {
  25. left=anode;
  26. }
  27.  
  28. void set_right_node(node* anode)
  29. {
  30. right=anode;
  31. }
  32.  
  33. node* get_left_node()
  34. {
  35. return left;
  36. }
  37.  
  38. node* get_right_node()
  39. {
  40. return right;
  41. }
  42.  
  43. void set_no_of_children(int a)
  44. {
  45. if(a<0 || a>2)
  46. return;
  47.  
  48. no_of_children=a;
  49. }
  50.  
  51. int get_no_of_children()
  52. {
  53. return no_of_children;
  54. }
  55. };
  56.  
  57. class tree
  58. {
  59. node* root;
  60.  
  61. public:
  62. void construct_tree()
  63. {
  64. queue <node*>q;
  65. root=new node;
  66. q.push(root);
  67. int d;
  68. cout<<"Enter the data of the root node: ";
  69. cin>>d;
  70. (q.front())->set_data(d);
  71.  
  72. while(!q.empty())
  73. {
  74. int no_of_children;
  75. cout<<"Enter the number of children of "<<q.front()->get_data()<<": ";
  76. cin>>no_of_children;
  77. q.front()->set_no_of_children(no_of_children);
  78.  
  79. for(int i=0;i<(q.front()->get_no_of_children());i++)
  80. {
  81. node* temp=new node;
  82. if(i==0)
  83. {
  84. int lc;
  85. cout<<"Enter the left child of: "<<q.front()->get_data()<<": ";
  86. cin>>lc;
  87. temp->set_data(lc);
  88. q.front()->set_left_node(temp);
  89. q.push(temp);
  90. }
  91. else if(i==1)
  92. {
  93. int rc;
  94. cout<<"Enter the right child of: "<<q.front()->get_data()<<": ";
  95. cin>>rc;
  96. temp->set_data(rc);
  97. q.front()->set_right_node(temp);
  98. q.push(temp);
  99. }
  100. }
  101.  
  102. if(q.front()->get_no_of_children()==0)
  103. {
  104. q.front()->set_left_node(0);
  105. q.front()->set_right_node(0);
  106. }
  107.  
  108. q.pop();
  109. }
  110.  
  111. }
  112.  
  113. void in_order_print()
  114. {
  115.  
  116. }
  117. };
  118.  
  119. int main()
  120. {
  121. tree t;
  122. t.construct_tree();
  123. t.in_order_print();
  124. }
  125.  
Success #stdin #stdout 0s 3280KB
stdin
Standard input is empty
stdout
Enter the data of the root node: Enter the number of children of 0: