PAT 甲 1135 红黑二叉树

题目要点:

解题的关键是理解题目所说的红黑的性质

There is a kind of balanced binary search tree named red-black tree in the data structure. It has the following 5 properties:

    (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.

从上面可以解读出:

是平衡二叉树,故可以根据前序遍历建立树

1.根节点是黑的,

2.红节点的左右孩子是黑的,

3.对于每个节点,从节点到子代叶子的所有简单路径都包含相同数量的黑色节点。(意思就是所有节点的左右子树的黑节点的数量相同)

#include<iostream>
#include<cmath>
#include<map> 
#include<vector>
#include<algorithm>
using namespace std;
int k,n,pre[35];
struct Node{
	int data;
	Node *lchild,*rchild;
};
void indata(){//输入函数
	for(int i=0;i<n;++i) cin>>pre[i];
};
Node * build(int pre[],int len){//建树
	if(len==0) return NULL;
	Node *root=new Node();
	root->data=pre[0];
	int i;
	for(i=0;i<len;++i){
		if(abs(pre[0])<abs(pre[i])) break;
	}
	root->lchild=build(&pre[1],i-1);
	root->rchild=build(&pre[i],len-i);
	return root;
}
bool flag3=true;
void judge2(Node *root){//红节点的孩子必须是黑的
	if(root==NULL) return ;
	judge2(root->lchild);
	judge2(root->rchild);
	if(root->data<0){
		if(root->lchild&&root->lchild->data<0) flag3=false;
		if(root->rchild&&root->rchild->data<0) flag3=false;
	}
} 
int judge3(Node *root){//左右子树相同
	if(root->lchild==NULL&&root->rchild==NULL) {
		if(root->data>0) return 1;
		if(root->data<0) return 0;
	}
	int lcount=0,rcount=0;
	if(root->lchild) lcount=judge3(root->lchild);
	if(root->rchild) rcount=judge3(root->rchild);
	return abs(lcount-rcount)+1;
}
bool judge(Node *root){
	if(root->data<0) return false;//根 
	if(judge3(root)>1) return false;
	flag3=true;
	judge2(root);
	if(flag3==false) return false;
	return true;
}
int main(){
	cin>>k;
	while(k--){
		cin>>n;
		indata();
		Node *root=build(pre,n);
		if(judge(root)) 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、付费专栏及课程。

余额充值