fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct Node {
  6. Node(int x) {
  7. key = x;
  8. left = nullptr;
  9. right = nullptr;
  10. }
  11. int key;
  12. Node* left;
  13. Node* right;
  14. };
  15. Node* BSTConstruction(const std::vector<int>& preorder, int& index, int low, int high) {
  16. if (index >= preorder.size()) {
  17. return nullptr;
  18. }
  19. int current_key = preorder[index];
  20. if (current_key <= low || current_key > high) {
  21. return nullptr;
  22. }
  23. Node* current_node = new Node(current_key);
  24. index++;
  25. current_node->left = BSTConstruction(preorder, index, low, current_key);
  26. current_node->right = BSTConstruction(preorder, index, current_key, high);
  27. return current_node;
  28. }
  29. void InOrder(const Node* node) {
  30. if (node == nullptr) {
  31. return;
  32. }
  33. InOrder(node->left);
  34. std::cout << node->key << ' ';
  35. InOrder(node->right);
  36. }
  37. void PostOrder(const Node* node) {
  38. if (node == nullptr) {
  39. return;
  40. }
  41. PostOrder(node->left);
  42. PostOrder(node->right);
  43. std::cout << node->key << ' ';
  44. }
  45. void PrintPostIn(const Node* root) {
  46. PostOrder(root);
  47. std::cout << '\n';
  48. InOrder(root);
  49. }
  50. void PostOrderDelete(Node* root) {
  51. if (root == nullptr) {
  52. return;
  53. }
  54. PostOrderDelete(root->left);
  55. PostOrderDelete(root->right);
  56. root->left = nullptr;
  57. root->right = nullptr;
  58. delete root;
  59. }
  60. int main() {
  61. std::ios_base::sync_with_stdio(false);
  62. std::cin.tie(NULL);
  63. int num;
  64. int index = 0;
  65. std::cin >> num;
  66. std::vector<int> keys(num);
  67. for (int i = 0; i != num; i++) {
  68. std::cin >> keys[i];
  69. }
  70. Node* root = BSTConstruction(keys, index, -1, 1000000000);
  71. PrintPostIn(root);
  72. PostOrderDelete(root);
  73. return 0;
  74. }
Success #stdin #stdout 0s 5284KB
stdin
7
4 2 1 3 6 5 7
stdout
1 3 2 5 7 6 4 
1 2 3 4 5 6 7