Description
给你一棵有 $n$ 个点的搜索二叉树的层序遍历序,问你它是不是一棵正则二叉树。单个测试点内共有 $T$ 组数据。
Solution
拿个队列存一下当前没确定是否放儿子的节点,然后直接模拟一下即可,在过程中存一下一个节点的值域限制即可。
正确性可以证明。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <cstdio> #define inf 999999999 #define maxN 100010 int a[maxN][3]; int f[maxN]; int read () { int x = 0; char c = getchar(); while(c < '0' || c > '9') { c = getchar(); } while(c >= '0' && c <= '9') { x = x * 10 + (c - '0'); c = getchar(); } return x; } int min (int x, int y) { return x < y ? x : y; } int max (int x, int y) { return x > y ? x : y; } int main () { int T = 0, n = 0; T = read(); while(T--) { n = read(); for(int i = 1;i <= n; i++) { a[i][0] = read(); a[i][1] = inf, a[i][2] = -inf; } if(!(n & 1)) { printf("NO\n"); continue; } int head = 1, tail = 1; f[head] = 1; bool flag = false; for(int i = 2;i <= n; i += 2) { while(head <= tail) { int x = f[head]; int L = a[x][1], R = a[x][2]; int lSonl = a[x][2]; int lSonr = min(a[x][1], a[x][0]); int rSonl = max(a[x][2], a[x][0]); int rSonr = a[x][1]; if(a[i][0] < lSonl || a[i][0] > lSonr || a[i + 1][0] < rSonl || a[i + 1][0] > rSonr) { head++; } else { break; } } if(head > tail) { printf("NO\n"); flag = true; break; } int x = f[head++]; a[i][1] = min(a[x][1], a[x][0]); a[i][2] = a[x][2]; a[i + 1][1] = a[x][1]; a[i + 1][2] = max(a[x][0], a[x][2]); f[++tail] = i; f[++tail] = i + 1; } if(!flag) { printf("YES\n"); } } return 0; }
|