1135. Is It A Red-Black Tree 解析

当时被红黑树吓傻了。。。然后走上了不归路。

主要还是没有理解红黑树也是一个顺序树,中序就是从小到大的顺序。然后结合给的前序建树。

后面判定的时候也是没有理解那个任意定点到树叶节点黑色节点数相同的意思。当作黑色节点高度这样去想会容易不少。

还是知道的太少了。。


#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <cstring>
#include <climits>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>

#define MAX 35

using namespace std;

int pre[MAX];
int in[MAX];

struct node{
	node * l, * r;
	int data;
	node(){l = r = NULL;};
};
typedef node * tree;
int n ,k;

bool cmp(int a , int b ){
	if( a < 0)
		a = -a;
	
	if (b < 0)
		b= -b;

	return a < b;
}

tree buildTree(int plow, int phigh ,int ilow, int ihigh , tree t){
	if(plow <= phigh){
		t = new node;
		t->l = NULL; t->r = NULL;
		t->data = pre[plow];
		int pos = -1;
		for(int i = ilow; i <= ihigh ; i++){
			if(in[i] == pre[plow]){
				pos = i;
				break;
			}
		}
		if(pos == -1)
			return NULL;

		t->l = buildTree(plow + 1 ,plow + pos - ilow ,ilow,pos-1,t->l);
		t->r = buildTree(plow + pos - ilow + 1, phigh, pos + 1 ,ihigh,t->r);
		return t;
	}
	else
		return NULL;
}


bool tag = true;

int GetHigh(tree t){//precolor 1 = black 0 = red
	if(t){
		if(t->data > 0)
			return max(GetHigh(t->l),GetHigh(t->r)) + 1;
		else
			return max(GetHigh(t->l),GetHigh(t->r));
	}
	else 
		return 1;
}

bool isRBT(tree t){

	if(tag && t && t->data < 0){//red
		if(!(!t->l || t->l->data > 0) || !(!t->r || t->r->data > 0))
			tag = false;
	}

	int l = 1 ,r = 1;
	if(t->l)
		l = GetHigh(t->l);
	if(t->r)
		r = GetHigh(t->r);
	if(l != r)
		tag = false;

	if(tag && t->l)
		tag = isRBT(t->l);
	if(tag && t->r)
		tag = isRBT(t->r);

	return tag;
}


int main(){
	
	scanf("%d",&n);
	for(int i = 0 ;i < n ;i++){
		scanf("%d",&k);
		for(int i = 0 ; i < k ; i ++){
			scanf("%d",&pre[i]);
			in[i] = pre[i];
		};
		sort(in,in+k,cmp);
		tree t = NULL;
		t= buildTree(0,k-1,0,k-1,t);

		if(t->data < 0)
			cout << "No" << endl;
		else{
			tag = true;
			if(isRBT(t))
				cout << "Yes" << endl;
			else
				cout << "No" << endl;
		}

	}
	

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值