Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <fstream>
- using namespace std;
- struct node {
- int key;
- vector < int > kids;
- };
- vector < node > arr;
- bool dfs(vector < node > &arr, int key, int pos, int left, int right)
- {
- if (key == -1)
- {
- return true;
- }
- if (key > right || key < left)
- {
- return false;
- }
- if (arr[pos].kids[1] == -1 && arr[pos].kids[0] ==-1)
- {
- return true;
- }
- int leftchild, rightchild, leftpos, rightpos;
- if (arr[pos].kids[0] != -1)
- {
- leftchild = arr[arr[pos].kids[0]].key;
- } else {
- leftchild = -1;
- }
- leftpos = arr[pos].kids[0];
- if (arr[pos].kids[1] != -1)
- {
- rightchild = arr[arr[pos].kids[1]].key;
- } else {
- rightchild = -1;
- }
- rightpos = arr[pos].kids[1];
- return (dfs(arr, leftchild, leftpos, left, key) && dfs(arr, rightchild, rightpos, key, right));
- }
- int main()
- {
- ifstream fin("check.in");
- ofstream fout("check.out");
- int n;
- fin >> n;
- arr.resize(n);
- int key, num1, num2;
- if (n == 0)
- {
- fout << "YES";
- } else {
- for (int i = 0; i < n; i++)
- {
- fin >> key;
- fin >> num1 >> num2;
- arr[i].key = key;
- arr[i].kids.push_back(num1 - 1);
- arr[i].kids.push_back(num2 - 1);
- }
- if (dfs(arr, arr[0].key, 0, INT_MIN, INT_MAX))
- {
- fout << "YES";
- } else {
- fout << "NO";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement