D_L3

Профил на дърво

Jan 25th, 2024
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <unordered_map>
  7.  
  8. using namespace std;
  9.  
  10.  
  11. struct Node {
  12.     Node *left;
  13.     Node *right;
  14.     int value;
  15.     Node(int value) {
  16.         this->value = value;
  17.         this->left = NULL;
  18.         this->right = NULL;
  19.     }
  20. };
  21.  
  22. class BST {
  23.    
  24. public:
  25.     BST() {
  26.         root = NULL;
  27.     }
  28.  
  29.     void insert(int value) {
  30.         root = insert(root, value);
  31.     }
  32.     //моят код е от ТУК
  33.     void printLeftProfile() {
  34.        getLeftMostIndexes(root, 0);
  35.       for(int i = min; i <= max; i++){
  36.           cout << getValue[i] << " ";
  37.       }
  38.     }
  39.     //до ТУК
  40. private:
  41.     //моят код е от ТУК
  42.     unordered_map<int, int> getValue; //height
  43.     int min = 0;
  44.     int max = 0;
  45.    
  46.     void getLeftMostIndexes(Node* node, int height){
  47.         if(node == nullptr)
  48.             return;
  49.        
  50.         if(getValue.count(height) == 0)
  51.             getValue[height] = node->value;
  52.        
  53.         if(height < min)
  54.             min = height;
  55.         if(height > max)
  56.             max = height;
  57.         getLeftMostIndexes(node->left, height + 1);
  58.         getLeftMostIndexes(node->right, height + 1);
  59.     }
  60.     //до ТУК
  61.     Node* root;
  62.  
  63.     Node* insert(Node *curNode, int value) {
  64.         if (curNode == NULL) {
  65.             curNode = new Node(value);
  66.         } else if (curNode->value < value) {
  67.             curNode->right = insert(curNode->right, value);
  68.         } else if (curNode->value > value) {
  69.             curNode->left = insert(curNode->left, value);
  70.         } else {
  71.             //if we already have this value at the tree - do nothing
  72.         }
  73.         return curNode;
  74.     }
  75. };
  76.  
  77. int main() {
  78.     int n;
  79.     cin >> n;
  80.     int value;
  81.     BST tree;
  82.     for(int i = 0 ; i < n; i++) {
  83.         cin >> value;
  84.         tree.insert(value);
  85.     }
  86.     tree.printLeftProfile();
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment