Advertisement
snowywhitee

Untitled

Dec 3rd, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4. using namespace std;
  5.  
  6. struct node {
  7.     int key;
  8.     vector < int > kids;
  9. };
  10.  
  11. vector < node > arr;
  12.  
  13. bool dfs(vector < node > &arr, int key, int pos, int left, int right)
  14. {
  15.     if (key == -1)
  16.     {
  17.         return true;
  18.     }
  19.     if (key > right || key < left)
  20.     {
  21.         return false;
  22.     }
  23.     if (arr[pos].kids[1] == -1 && arr[pos].kids[0] ==-1)
  24.     {
  25.         return true;
  26.     }
  27.     int leftchild, rightchild, leftpos, rightpos;
  28.     if (arr[pos].kids[0] != -1)
  29.     {
  30.         leftchild = arr[arr[pos].kids[0]].key;
  31.     } else {
  32.         leftchild = -1;
  33.     }
  34.     leftpos = arr[pos].kids[0];
  35.     if (arr[pos].kids[1] != -1)
  36.     {
  37.         rightchild = arr[arr[pos].kids[1]].key;
  38.     } else {
  39.         rightchild = -1;
  40.     }
  41.     rightpos = arr[pos].kids[1];
  42.    
  43.     return (dfs(arr, leftchild, leftpos, left, key) && dfs(arr, rightchild, rightpos, key, right));
  44. }
  45.  
  46. int main()
  47. {
  48.     ifstream fin("check.in");
  49.     ofstream fout("check.out");
  50.    
  51.     int n;
  52.     fin >> n;
  53.     arr.resize(n);
  54.     int key, num1, num2;
  55.     if (n == 0)
  56.     {
  57.         fout << "YES";
  58.     } else {
  59.         for (int i = 0; i < n; i++)
  60.         {
  61.             fin >> key;
  62.             fin >> num1 >> num2;
  63.             arr[i].key = key;
  64.             arr[i].kids.push_back(num1 - 1);
  65.             arr[i].kids.push_back(num2 - 1);
  66.         }
  67.        
  68.         if (dfs(arr, arr[0].key, 0, INT_MIN, INT_MAX))
  69.         {
  70.             fout << "YES";
  71.         } else {
  72.             fout << "NO";
  73.         }
  74.     }
  75.    
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement