irapilguy

Untitled

Nov 11th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <iostream>
  3. using namespace std;
  4. struct Node {
  5.     int data;
  6.     Node *left;
  7.     Node *right;
  8.     Node(int x) {
  9.         data = x;
  10.         left = right = NULL;
  11.     }
  12. };
  13. void createNode(int x, Node *&tree) {
  14.     if (tree == NULL) tree = new Node(x);
  15.     if (x < tree->data) {
  16.         if (tree->left != NULL)  createNode(x, tree->left);
  17.         else tree->left = new Node(x);
  18.     }
  19.     if (x > tree->data) {
  20.         if (tree->right != NULL) createNode(x, tree->right);
  21.         else tree->right = new Node(x);
  22.     }
  23. }
  24.  
  25. void search(int x, Node *tree, int i, char *command) {
  26.     if (tree == NULL) {
  27.         cout << "NO ROUTE";
  28.         return;
  29.     }
  30.     if (x == tree->data) {
  31.         command[i] = 'S';
  32.         command[i + 1] = '\0';
  33.         if (command != '\0') cout << command<<"\n";
  34.     }
  35.     if (x < tree->data) {
  36.         command[i] = 'L';
  37.         search(x, tree->left, i + 1,command);
  38.     }
  39.     if (x > tree->data) {
  40.         command[i] = 'R';
  41.         search(x, tree->left, i + 1,command);
  42.     }
  43. }
  44. int main() {
  45.     Node *tree = NULL;
  46.     int x;
  47.     cin >> x;
  48.     while (x != 0) {
  49.         createNode(x, tree);
  50.         cin >> x;
  51.     }
  52.     int p;
  53.     cin >> p;
  54.     for (int j = 0; j < p; j++) {
  55.         int x;
  56.         cin >> x;
  57.         char *command = new char[1000];
  58.         search(x, tree, 0, command);
  59.     }
  60.     return 0;
  61. }
Add Comment
Please, Sign In to add comment