There is a kind of balanced binary search tree named red-black tree in the data structure. It has the following 5 properties:
(1) Every node is either red or black.(2) The root is black.(3) Every leaf (NULL) is black.(4) If a node is red, then both its children are black.(5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.For example, the tree in Figure 1 is a red-black tree, while the ones in Figure 2 and 3 are not.
Figure 1Figure 2Figure 3For each given binary search tree, you are supposed to tell if it is a legal red-black tree.
Each input file contains several test cases. The first line gives a positive integer K (≤30) which is the total number of cases. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the preorder traversal sequence of the tree. While all the keys in a tree are positive integers, we use negative signs to represent red nodes. All the numbers in a line are separated by a space. The sample input cases correspond to the trees shown in Figure 1, 2 and 3.
For each test case, print in a line "Yes" if the given tree is a red-black tree, or "No" if not.
作者
CHEN, Yue
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; const int maxn = 100006; vector<int> pre, in, v(maxn); bool cmp(int a, int b) { return abs(a) < abs(b); } void getTree(int index, int preleft, int preright, int inleft, int inright) { if (inleft > inright) { return; } v[index] = pre[preleft]; int i = 0; while (in[i] != pre[preleft]) { i++; } getTree(index * 2, preleft + 1, preleft + i - inleft, inleft, i - 1); getTree(index * 2 + 1, preleft + i - inleft + 1, preright, i + 1, inright); } bool judge1(int index) { if (v[index] == 0) { return true; } if (v[index] < 0) { if (v[index * 2] != 0 && v[index * 2] < 0) { return false; } if (v[index * 2 + 1] != 0 && v[index * 2 + 1] < 0) { return false; } } return judge1(index * 2) && judge1(index * 2 + 1); } int getnum(int index) { if (v[index] == 0) { return 0; } int l = getnum(index * 2); int r = getnum(index * 2 + 1); return v[index] > 0 ? max(l, r) + 1 : max(l, r); } bool judge2(int index) { if (v[index] == 0) { return true; } int l = getnum(index * 2); int r = getnum(index * 2 + 1); if (l != r) { return false; } return judge2(index * 2) && judge2(index * 2 + 1); } int main() { freopen("in.txt", "r", stdin); int k, n; cin >> k; v.resize(maxn);//应该是数组v不够大,2的30次方太大了,没有那么大的内存 for (int i = 0; i < k; i++) { cin >> n; pre.resize(n + 1), in.resize(n + 1); for (int i = 1; i <= n; i++) { cin >> pre[i]; } in = pre; sort(in.begin(), in.end(), cmp); getTree(1, 1, n, 1, n); if (v[0] < 0 || judge1(1) == false || judge2(1) == false) { cout << "No" << endl; } else { cout << "Yes" << endl; } } return 0; }