Advertisement
Guest User

ыы

a guest
Feb 16th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <queue>
  4. using namespace std;
  5.  
  6. class TreeNode {
  7. public:
  8.     TreeNode(int key) : Key(key), Left(0), Right(0) {}
  9.     int Key;
  10.     TreeNode* Left;
  11.     TreeNode* Right;
  12. };
  13.  
  14. class Tree {
  15. public:
  16.     Tree() :Root(0) {
  17.     }
  18.     ~Tree() {
  19.         DestroyTreeNode(Root);
  20.     }
  21.     void Insert(int n);
  22.     void LeftStraightPrint(TreeNode* root) {
  23.         if (root = NULL) {
  24.             return;
  25.         }
  26.         cout << root->Key << endl;
  27.         LeftStraightPrint(root->Left);
  28.         LeftStraightPrint(root->Right);
  29.     };
  30.     TreeNode *get_root() {
  31.         return Root;
  32.     }
  33. private:
  34.     static void DestroyTreeNode(TreeNode* tn) {
  35.         if (tn) {
  36.             DestroyTreeNode(tn->Left);
  37.             DestroyTreeNode(tn->Right);
  38.             delete tn;
  39.         }
  40.     }
  41. private:
  42.     TreeNode* Root;
  43. };
  44.  
  45. void Tree::Insert(int n) {
  46.     TreeNode** cur = &Root;
  47.     while (*cur) {
  48.         TreeNode& tn = **cur;
  49.         if (n < tn.Key)
  50.             cur = &tn.Left;
  51.         else if (n > tn.Key)
  52.             cur = &tn.Right;
  53.         else return;
  54.     }
  55.     *cur = new TreeNode(n);
  56. }
  57.  
  58. int main() {
  59.     ifstream fin("input.txt");
  60.     ofstream fout("output.txt");
  61.  
  62.     Tree MyTree;
  63.     int temp;
  64.     while (!fin.eof()) {
  65.         fin >> temp;
  66.         MyTree.Insert(temp);
  67.     }
  68.     MyTree.LeftStraightPrint(MyTree.get_root());
  69.  
  70.     fin.close();
  71.     fout.close();
  72.     system("pause");
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement