1135 Is It A Red-Black Tree (30分) 红黑树判定

原题目参见1135 Is It A Red-Black Tree (30分),要求判断一个树的先根序列
是否能构成红黑树。由于红黑树是搜索二叉树,所以给定一个先根序列,可以唯一生成一棵搜索二叉树,如果无法生成搜索二叉树,则判否。再由题目给的红黑树的生成条件,判断该序列是否为合法的红黑树。

(1) Every node is either red or black.
(2) The root is black.
(3) Every leaf (NULL) is black.
(4) If a node is red, then both its children are black.
(5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.

下面是AC代码(C++版本)。

#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

const int maxn = 50;
struct Node {
	int data, color, bd; // a[l]>0,1表示黑树,0表示红树。
	Node* lchild, * rchild;
	void print() {
		printf("data = %d. color = %d. \n", data, color);
	}
};

int a[maxn], b[maxn]; //a: original data. b: positive data.
bool bstf, brtf; // binary search tree flag, black red tree flag.

Node* createNode(int data, int color) {
	Node* root = new Node;
	root->data = data;
	root->lchild = NULL;
	root->rchild = NULL;
	root->color = color;
	return root;
}

// Use b[] to create a binary search tree.
int createTree(int l, int r, Node*& root) {
	if (l == r) {
		root = createNode(b[l], a[l]>0);
		return 0;
	}
	int rootd = b[l];
	int rid = l+1;
	root = createNode(b[l], a[l]>0);
	for (; rid <= r; rid++) {
		if (b[rid] > rootd) {
			break; //找到第一个比根节点大的节点。在该节点的右侧应该所有的节点都比根节点小。
		}
	}
	for (int testid = rid; testid <= r; testid++) {
		if (b[testid] < rootd) {
			bstf = 0;//不符合二叉查找树的先根遍历序列要求。
			return 0;
		}
	}
	if (rid != l + 1) {
		//有左子树。
		createTree(l + 1, rid - 1, root->lchild);
	}
	if (rid != r + 1) {
		//有右子树。
		createTree(rid, r, root->rchild);
	}
	return 1;
}

int getBNum(Node* root) {
	int l = (root->lchild == NULL || (root->lchild && root->lchild->color));
	int r = (root->rchild == NULL || (root->rchild && root->rchild->color));
	return l + r;
}

int judgeBRT(Node* root) {
	if (root == NULL) {
		return 1;
	}
	int lbn = judgeBRT(root->lchild);
	int rbn = judgeBRT(root->rchild);
	if (lbn != rbn || (!root->color&&getBNum(root)<2)) {
		brtf = 0;
	}
	return lbn+root->color;
}

int main()
{
	int k, n, t;
	scanf("%d", &k);
	for (int i = 0; i < k; i++) {
		scanf("%d", &n);
		memset(a, 0, sizeof(a));
		memset(b, 0, sizeof(b));
		bstf = 1;
		brtf = 1;
		Node* root = NULL;
		for (int j = 0; j < n; j++) {
			scanf("%d", &a[j]);
			b[j] = abs(a[j]);
		}
		if (a[0] > 0) {
			createTree(0, n - 1, root);
			if (bstf) {
				judgeBRT(root);
				if (brtf) {
					printf("Yes\n");
				}
				else {
					printf("No\n");
				}
			}
			else {
				printf("No\n");
			}
		}
		else {
			printf("No\n");
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ProfSnail

谢谢老哥嗷

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值