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 parent = key;
- int leftchild, rightchild, leftpos, rightpos;
- leftchild = rightchild = leftpos = rightpos = -1;
- if (arr[pos].kids[0] != -1)
- {
- leftchild = arr[arr[pos].kids[0]].key;
- leftpos = arr[pos].kids[0];
- }
- if (arr[pos].kids[1] != -1)
- {
- rightchild = arr[arr[pos].kids[1]].key;
- rightpos = arr[pos].kids[1];
- }
- if (leftpos != -1 && rightpos != -1)
- {
- if (leftchild > parent || rightchild < parent)
- {
- return false;
- } else {
- return (dfs(arr, leftchild, leftpos) && dfs(arr, rightchild, rightpos));
- }
- } else if (leftpos == -1 && rightpos == -1)
- {
- return true;
- } else if (leftpos != -1 && rightpos == -1)
- {
- if (leftchild > parent)
- {
- return false;
- } else {
- return dfs(arr, leftchild, leftpos);
- }
- } else if (leftpos == -1 && rightpos != -1)
- {
- if (rightchild < parent)
- {
- return false;
- } else {
- return dfs(arr, rightchild, rightpos);
- }
- }
- }
- int main()
- {
- ifstream fin("1.txt");
- ofstream fout("2.txt");
- int n;
- fin >> n;
- arr.resize(n);
- int key, num1, num2;
- if (n == 0)
- {
- cout << "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))
- {
- cout << "YES";
- } else {
- cout << "NO";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement