Advertisement
smatskevich

Lesson22

Feb 29th, 2024
710
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. struct Node {
  4.   int Data;
  5.   Node* Left = nullptr;
  6.   Node* Right = nullptr;
  7. };
  8.  
  9. void DFS(Node* node) {
  10.   cout << node->Data << " ";
  11.   if (node->Left) {
  12.     DFS(node->Left);
  13.     cout << node->Data << " ";
  14.   }
  15.   if (node->Right) {
  16.     DFS(node->Right);
  17.     cout << node->Data << " ";
  18.   }
  19. }
  20.  
  21. int main1() {
  22.   Node* root = nullptr;
  23.   int x;
  24.   while (cin >> x, x != 0) {
  25.     if (!root) {
  26.       root = new Node();
  27.       root->Data = x;
  28.       continue;
  29.     }
  30.     Node* node = root;
  31.     while (true) {
  32.       if (node->Data == x) break;
  33.       if (node->Data < x) {
  34.         if (node->Right == nullptr) {
  35.           node->Right = new Node();
  36.           node->Right->Data = x;
  37.           break;
  38.         }
  39.         node = node->Right;
  40.       } else {
  41.         if (node->Left == nullptr) {
  42.           node->Left = new Node();
  43.           node->Left->Data = x;
  44.           break;
  45.         }
  46.         node = node->Left;
  47.       }
  48.     }
  49.   }
  50.   DFS(root);
  51.   return 0;
  52. }
  53.  
  54. void PreOrderDFS(vector<vector<int>>& t, int u, int p) {
  55.   cout << u << "\n";
  56.   for (int v : t[u]) {
  57.     if (v != p)
  58.       PreOrderDFS(t, v, u);
  59.   }
  60. }
  61.  
  62. int main() {
  63.   int n; cin >> n;
  64.   vector<vector<int>> t(n + 1);
  65.   for (int i = 0; i < n - 1; ++i) {
  66.     int u, v; cin >> u >> v;
  67.     t[u].push_back(v);
  68.     t[v].push_back(u);
  69.   }
  70.   PreOrderDFS(t, 1, -1);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement