当时被红黑树吓傻了。。。然后走上了不归路。
主要还是没有理解红黑树也是一个顺序树,中序就是从小到大的顺序。然后结合给的前序建树。
后面判定的时候也是没有理解那个任意定点到树叶节点黑色节点数相同的意思。当作黑色节点高度这样去想会容易不少。
还是知道的太少了。。
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <cstring>
#include <climits>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#define MAX 35
using namespace std;
int pre[MAX];
int in[MAX];
struct node{
node * l, * r;
int data;
node(){l = r = NULL;};
};
typedef node * tree;
int n ,k;
bool cmp(int a , int b ){
if( a < 0)
a = -a;
if (b < 0)
b= -b;
return a < b;
}
tree buildTree(int plow, int phigh ,int ilow, int ihigh , tree t){
if(plow <= phigh){
t = new node;
t->l = NULL; t->r = NULL;
t->data = pre[plow];
int pos = -1;
for(int i = ilow; i <= ihigh ; i++){
if(in[i] == pre[plow]){
pos = i;
break;
}
}
if(pos == -1)
return NULL;
t->l = buildTree(plow + 1 ,plow + pos - ilow ,ilow,pos-1,t->l);
t->r = buildTree(plow + pos - ilow + 1, phigh, pos + 1 ,ihigh,t->r);
return t;
}
else
return NULL;
}
bool tag = true;
int GetHigh(tree t){//precolor 1 = black 0 = red
if(t){
if(t->data > 0)
return max(GetHigh(t->l),GetHigh(t->r)) + 1;
else
return max(GetHigh(t->l),GetHigh(t->r));
}
else
return 1;
}
bool isRBT(tree t){
if(tag && t && t->data < 0){//red
if(!(!t->l || t->l->data > 0) || !(!t->r || t->r->data > 0))
tag = false;
}
int l = 1 ,r = 1;
if(t->l)
l = GetHigh(t->l);
if(t->r)
r = GetHigh(t->r);
if(l != r)
tag = false;
if(tag && t->l)
tag = isRBT(t->l);
if(tag && t->r)
tag = isRBT(t->r);
return tag;
}
int main(){
scanf("%d",&n);
for(int i = 0 ;i < n ;i++){
scanf("%d",&k);
for(int i = 0 ; i < k ; i ++){
scanf("%d",&pre[i]);
in[i] = pre[i];
};
sort(in,in+k,cmp);
tree t = NULL;
t= buildTree(0,k-1,0,k-1,t);
if(t->data < 0)
cout << "No" << endl;
else{
tag = true;
if(isRBT(t))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
}
return 0;
}