Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class Bnode {
  7. public:
  8. string val;
  9. Bnode* pLeft;
  10. Bnode* pRight;
  11. Bnode(string s) { val = s; pLeft = pRight = nullptr; }
  12. };
  13.  
  14. class Btree {
  15. private:
  16. Bnode* root;
  17. Bnode* insert_at_sub(string s, Bnode* p);
  18. void print_sub(Bnode* p);
  19. public:
  20. Btree() { root = NULL;}
  21. void insert(string s)
  22. {
  23. root = insert_at_sub(s, root);
  24. }
  25. void print() { print_sub(root); }
  26.  
  27. };
  28.  
  29.  
  30. int main() {
  31. Btree my_tree;
  32. int stop = 0;
  33. string sPrompt = "Enter a name (ENTER when done): ";
  34. string sInput = "";
  35.  
  36. while (true) {
  37. cout << sPrompt;
  38. getline(cin, sInput);
  39. if (sInput.size() == 0) {
  40. break;
  41. }
  42. my_tree.insert(sInput);
  43. }
  44. cout << "Here are the names, in order." << endl;
  45. my_tree.print();
  46. cin >> stop;
  47. return 0;
  48. }
  49.  
  50.  
  51. Bnode* Btree::insert_at_sub(string s, Bnode* p) {
  52. if (!p) {
  53. return new Bnode(s);
  54. }
  55. else if (s < p->val) {
  56. p->pLeft = insert_at_sub(s, p->pLeft);
  57. }
  58. else if (s > p->val) {
  59. p->pRight = insert_at_sub(s, p->pRight);
  60. }
  61. return p;
  62. }
  63.  
  64. void Btree::print_sub(Bnode* p) {
  65. if (p) {
  66. print_sub(p->pLeft);
  67. cout << p->val << endl;
  68. print_sub(p->pRight);
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement