PAT Class A 1135 [Is It A Red-Black Tree] (30)

Analysis: Some judgment questions are paper tigers. (Don't be frightened by the red and black trees, the more you think the concept is very difficult, the more difficult the test may not be, at least not to ask you to achieve the red and black tree ha ha ha ha ha ha ha ha). In fact, this kind of question is a bit like simulating according to the meaning of the question. First, BST is built in order, and then negative sign is red, and then bfs is used to traverse each node and judge the right one. Whether the front node meets the requirements. PS: Happy once

#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;

typedef struct Tree{
	int val, neg;
	struct Tree *l, *r;
}Tree;

int abs(int num){
	if(num < 0) num = -num;
	return num;
}
int isRedBlackTree = 1, first = 0, cnt = 0;
Tree *insert(Tree *root, int val){
	if(root == NULL) {
		root = (Tree *)malloc(sizeof(Tree));
		root->val = abs(val);
		if(val < 0) root->neg = 1;
		root->l = root->r = NULL;
		return root;
	}
	if(root->val > abs(val)){
		root->l = insert(root->l, val);
	}
	else root->r = insert(root->r, val);
	return root;
}
void dfsPath(Tree *root, int sum){
	if(root == NULL){
		if(!first){
			first = 1;
			cnt = sum;
		}
		else {
			if(cnt != sum) isRedBlackTree = 0;
		}
		return ;
	}
	if(root->neg != 1) sum++;
	dfsPath(root->l, sum);
	dfsPath(root->r, sum);
}
void bfs(Tree *root){
	queue<Tree *> q;
	q.push(root);
	if(root->neg == 1) isRedBlackTree = 0;
	while(isRedBlackTree && !q.empty()){
		Tree *cur = q.front();
		q.pop();
		first = 0;
		dfsPath(cur, 0);
		if(cur->l) q.push(cur->l);
		if(cur->r) q.push(cur->r);
		if(cur->neg == 1) {
			if(cur->l && cur->l->neg == 1)  isRedBlackTree = 0;
			if(cur->r && cur->r->neg == 1)  isRedBlackTree = 0;
		}
	}
	if(isRedBlackTree) printf("Yes\n");
	else printf("No\n");
}
int main(){
	//freopen("in.txt", "r", stdin);
	int n, i, T, num;
	scanf("%d", &T);
	while(T--){
		isRedBlackTree = 1;
		Tree *root = NULL;
		scanf("%d", &n);
		for(i = 0; i<n; i++){
			scanf("%d", &num);
			root = insert(root, num);
		}
		bfs(root);
	}
	
	return 0;
} 

 

Posted by blankextacy on Mon, 04 Feb 2019 13:51:16 -0800