PAT 甲级A1335 后两个测试点错误原因

题中leaf结点指的是空结点,不是指child都为空的结点。

只需要从根结点出发,遍历树,达到空结点时,存储黑色结点数,之后判断所有空结点的黑色结点树是否一致即可。

#include
#include
using namespace std;
struct Node {
	int key;
	int color;
	Node* left;
	Node* right;
};
Node* Creattree(Node* root, int key,int color) {
	if (root == NULL) {
		root = new Node();
		root->key = key;
		root->left = NULL;
		root->right = NULL;
		root->color = color;
		return root;
	}
	else if (key <= root->key) {
		root->left = Creattree(root->left, key,  color);
	}
	else root->right = Creattree(root->right, key,  color);
	return root;
}
int flag = 1,num=0,blackone=0;
int same[50];
void judge(Node* root) {
	if (root == NULL)
    {
        same[num++] = blackone;
        return;
    }
    if(root->key==0)flag=0;
	if (root->color == -1) {
		if (root->left != NULL && root->left->color == -1) flag = 0;
		if (root->right != NULL && root->right->color == -1)flag = 0;
	}
	else blackone++;
	judge(root->left);
	judge(root->right);
	if (root->color == 1)blackone--;
}
int main() {
	int q,n;
	scanf("%d", &q);
	for (int i = 0; i < q; i++) {
        Node* root;
		scanf("%d", &n);
		root = NULL;
        int first;
		for (int j = 0; j < n; j++) {
			int w;
			scanf("%d", &w);
            if(j==0)first = w;
			if (w < 0) root = Creattree(root, -w, -1);
			else root = Creattree(root, w, 1);
		}
		flag = 1, num = 0, blackone = 0;
		fill(same, same + 50, 0);
		if (first< 0)	flag = 0;
		else
		{
			judge(root);
			for (int e = 0; e < num-1; e++) {
				if (same[e] != same[e + 1])flag = 0;
			}
		}
		if (flag == 1)printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

你可能感兴趣的:(PAT甲级)