Advertisement
Svizel_pritula

serialize_tree

Apr 23rd, 2022
859
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <vector>
  2. #include <memory>
  3. #include <iostream>
  4.  
  5. struct node
  6. {
  7.     std::vector<std::shared_ptr<node>> children;
  8. };
  9.  
  10. int serialize_tree(std::vector<std::vector<int>> &result, std::shared_ptr<node> root)
  11. {
  12.     int index = result.size();
  13.     result.push_back({});
  14.  
  15.     for (std::shared_ptr<node> child : root->children)
  16.     {
  17.         result.at(index).push_back(serialize_tree(result, child));
  18.     }
  19.  
  20.     return index;
  21. }
  22.  
  23. std::shared_ptr<node> generate_tree(int depth)
  24. {
  25.     std::shared_ptr<node> root = std::make_shared<node>();
  26.  
  27.     for (int i = 0; i < depth; i++)
  28.     {
  29.         root->children.push_back(generate_tree(depth - 1));
  30.     }
  31.  
  32.     return root;
  33. }
  34.  
  35. void print_serialized_tree(std::vector<std::vector<int>> tree)
  36. {
  37.     for (size_t i = 0; i < tree.size(); i++)
  38.     {
  39.         for (size_t j = 0; j < tree[i].size(); j++)
  40.         {
  41.             if (j != 0)
  42.                 std::cout << ' ';
  43.             std::cout << tree[i][j];
  44.         }
  45.  
  46.         std::cout << std::endl;
  47.     }
  48. }
  49.  
  50. int main()
  51. {
  52.     std::shared_ptr<node> root = generate_tree(5);
  53.  
  54.     std::vector<std::vector<int>> result;
  55.     serialize_tree(result, root);
  56.  
  57.     print_serialized_tree(result);
  58.     return 0;
  59. }
  60.  
Advertisement
RAW Paste Data Copied
Advertisement