Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Advanced/C++/1135] Suggestion #148

Open
zzzbf opened this issue Jul 5, 2020 · 0 comments
Open

[Advanced/C++/1135] Suggestion #148

zzzbf opened this issue Jul 5, 2020 · 0 comments

Comments

@zzzbf
Copy link

zzzbf commented Jul 5, 2020

一次前序遍历即可,不需要遍历两次

#include<iostream>
#include<vector>
#include<set>

using namespace std;

struct node {
	int val;
	node *left, *right;
};

node *Insert(int val, node *root)
{
	if (root == NULL) {
		root = new node();
		root->val = val;
		root->left = root->right = NULL;
	}
	else if (abs(val) <= abs(root->val))
		root->left = Insert(val, root->left);
	else
		root->right = Insert(val, root->right);
	return root;
}

bool preOrderJudge(node* root, int blackCnt, set<int> &cnt) {
	if (root == NULL) {
		cnt.insert(blackCnt);
		return true;
	}
	
	if(root->val<0 && ((root->right && root->right->val<0)|| 
		(root->left && root->left->val < 0))) return false;
	if (preOrderJudge(root->left, root->val < 0 ? blackCnt : blackCnt + 1, cnt))
		return preOrderJudge(root->right, root->val < 0 ? blackCnt : blackCnt + 1, cnt);
	return false;
}

int main()
{
	int testN, nodesN, val;
	cin >> testN;
	for (int i = 0; i < testN; i++) {
		cin >> nodesN;
		node* root = NULL;
		set<int> cnt;
		for (int j = 0; j < nodesN; j++) {
			cin >> val;
			root = Insert(val, root);
		}
		// 根结点必须为黑结点
		// 红色结点的孩子为黑色结点
		// 所有路径有相同数量的黑色结点

		bool flag = preOrderJudge(root, 0, cnt);
		printf("%s\n", root->val > 0 && flag && cnt.size() == 1 ? "Yes" : "No");
	}
	return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant