一开始是用动态链表做的,怎么都过不了,第二次看了网上柳婼大神的代码,用指针做过了。
附柳婼大神链接
动态链表代码:
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct Node{
int data;
bool color; // true -> 黑 false -> 红
int lchild,rchild;
Node(int d,bool c){
data = d;
color = c;
lchild = -1;
rchild = -1;
}
};
int preOrder[40];
int inOrder[40];
vector<Node> nodes;
int n;
bool cmp(int a,int b){
return abs(a) < abs(b);
}
void init(){
scanf("%d",&n);
for(int i = 0;i < n;i++){
scanf("%d",&preOrder[i]);
inOrder[i] = preOrder[i];
}
sort(inOrder,inOrder + n,cmp);
}
int buildTree(int preL,int preR,int inL,int inR){
if(preR < preL)
return -1;
int data = preOrder[preL];
Node root(abs(data),data >= 0);
nodes.push_back(root);
int index = nodes.size() - 1;
// 在中序遍历中找根节点的位置
int rootInInOrder;
for(int i = inL;i <= inR;i++){
if(inOrder[i] == data){
rootInInOrder = i;
break;
}
}
int leftSubTree = rootInInOrder - inL;
nodes[index].lchild = buildTree(preL + 1,preL + leftSubTree,inL,rootInInOrder - 1);
nodes[index].rchild = buildTree(preL + leftSubTree + 1,preR,rootInInOrder + 1,inR);
return index;
}
int blackNum = -1;
int tempBlackNum = 0;
bool isRedBlackTree(int root){
if(root == -1)
return true;
if(root == 0 && nodes[0].color == false) // 若根节点是红色,直接返回
return false;
if(nodes[root].color == true) // 若该节点是黑色,黑色节点数量加一
tempBlackNum++;
else{ // 若该节点是红色,看其两个孩子是否是黑色
bool lcolor,rcolor;
lcolor = (nodes[root].lchild != -1 && nodes[nodes[root].lchild].color == false) ? false : true;
rcolor = (nodes[root].rchild != -1 && nodes[nodes[root].rchild].color == false) ? false : true;
if(!(lcolor && rcolor))
return false;
}
if(nodes[root].lchild == -1 && nodes[root].rchild == -1){ // 若到达叶节点
if(blackNum == -1){// 第一次到达叶节点,更新从根到叶黑节点数量
blackNum = tempBlackNum;
if(nodes[root].color == true)
tempBlackNum--;
return true;
}
else if(blackNum != tempBlackNum) // 两条路径黑节点数量不相等
return false;
else{
if(nodes[root].color == true)
tempBlackNum--;
return true;
}
}
else if(nodes[root].lchild != -1 && nodes[root].rchild != -1){ // 若既有左孩子又有右孩子
bool l,r;
l = isRedBlackTree(nodes[root].lchild);
r = isRedBlackTree(nodes[root].rchild);
if(nodes[root].color == true)
tempBlackNum--;
return r && l;
}
else if(nodes[root].lchild != -1){ // 若仅有左孩子
bool l;
l = isRedBlackTree(nodes[root].lchild);
if(nodes[root].color == true)
tempBlackNum--;
return l;
}
else if(nodes[root].rchild != -1){ // 若仅有右孩子
bool r;
r = isRedBlackTree(nodes[root].rchild);
if(nodes[root].color == true)
tempBlackNum--;
return r;
}
}
int main(){
int k;
scanf("%d",&k);
for(int i = 0;i < k;i++){
nodes.clear();
init();
buildTree(0,n - 1,0,n - 1);
printf(isRedBlackTree(0) ? "Yes\n" : "No\n");
blackNum = -1;
tempBlackNum = 0;
}
system("pause");
return 0;
}