fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct BTree{
  5. int data;
  6. BTree *left;
  7. BTree *right;
  8. };
  9. BTree *root = NULL;
  10.  
  11. BTree *create_node(int item)
  12. {
  13. BTree *New = new BTree;
  14.  
  15. New->data = item;
  16. New->left = NULL;
  17. New->right = NULL;
  18.  
  19. return New;
  20. }
  21.  
  22. void add_left_child(BTree *parent, BTree *leftchild)
  23. {
  24. parent->left = leftchild;
  25. }
  26.  
  27. void add_right_child(BTree *parent, BTree *rightchild)
  28. {
  29. parent->right = rightchild;
  30. }
  31.  
  32. BTree *create_tree()
  33. {
  34. BTree *two = create_node(2);
  35. BTree *seven = create_node(7);
  36. BTree *nine = create_node(9);
  37.  
  38. add_left_child(two, seven);
  39. add_right_child(two, nine);
  40.  
  41. BTree *one = create_node(1);
  42. BTree *six = create_node(6);
  43.  
  44. add_left_child(seven, one);
  45. add_right_child(seven, six);
  46.  
  47. BTree *eight = create_node(8);
  48.  
  49. add_right_child(nine, eight);
  50.  
  51. BTree *five = create_node(5);
  52. BTree *ten = create_node(10);
  53.  
  54. add_left_child(six, five);
  55. add_right_child(six, ten);
  56.  
  57. BTree *three = create_node(3);
  58. BTree *four = create_node(4);
  59.  
  60. add_left_child(eight, three);
  61. add_right_child(eight, four);
  62.  
  63. return two;
  64. }
  65.  
  66. void preorder(BTree *Node)
  67. {
  68. if(Node == NULL)return;
  69. cout<<Node->data<<" ";
  70. preorder(Node->left);
  71. preorder(Node->right);
  72. }
  73.  
  74. void inorder(BTree *Node)
  75. {
  76. if(Node == NULL)return;
  77. inorder(Node->left);
  78. cout<<Node->data<<" ";
  79. inorder(Node->right);
  80. }
  81.  
  82. void postorder(BTree *Node)
  83. {
  84. if(Node == NULL)return;
  85. postorder(Node->left);
  86. postorder(Node->right);
  87. cout<<Node->data<<" ";
  88. }
  89.  
  90.  
  91. int main()
  92. {
  93. root = create_tree();
  94.  
  95. preorder(root);
  96. cout<<endl;
  97. inorder(root);
  98. cout<<endl;
  99. postorder(root);
  100. cout<<endl;
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108. }
  109.  
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
2 7 1 6 5 10 9 8 3 4 
1 7 5 6 10 2 9 3 8 4 
1 5 10 6 7 3 4 8 9 2