fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct Node
  6. {
  7. int val;
  8. Node* left;
  9. Node* right;
  10.  
  11. Node(int v)
  12. {
  13. val = v;
  14. left = right = nullptr;
  15. }
  16. };
  17.  
  18.  
  19. class Tree
  20. {
  21. Node* root;
  22.  
  23. Tree()
  24. {
  25. root = nullptr;
  26. }
  27.  
  28. public:
  29.  
  30. static void insert(int x, Node*& node)
  31. {
  32. if (node == nullptr)
  33. {
  34. node = new Node(x);
  35. }
  36. else
  37. {
  38. if (x < node->val)
  39. insert(x, node->left);
  40. else
  41. insert(x, node->right);
  42. }
  43. }
  44.  
  45. static Tree* populateTree(vector<string> dataVec)
  46. {
  47. Tree* t= new Tree();
  48. for (int i = 0; i < dataVec.size(); i++)
  49. {
  50. insert(stoi(dataVec[i]), t->root);
  51. }
  52. return t;
  53. }
  54.  
  55. static void printTree(Node* node, string s)
  56. {
  57. if(node == nullptr) return;
  58. cout<<s<< "+"<<node->val <<endl;
  59. s += "----";
  60. printTree(node->left,s);
  61. printTree(node->right, s);
  62. }
  63.  
  64. static void printTree(Tree* t)
  65. {
  66. if(t)
  67. {
  68. printTree(t->root, "");
  69. }
  70. }
  71. };
  72.  
  73. int main() {
  74. Tree* t = Tree::populateTree({"70", "2", "7", "20", "41", "28", "20", "51", "91"});
  75. Tree::printTree(t);
  76. return 0;
  77. }
Success #stdin #stdout 0s 4324KB
stdin
Standard input is empty
stdout
+70
----+2
--------+7
------------+20
----------------+41
--------------------+28
------------------------+20
--------------------+51
----+91