PAT甲级1135 Is It A Red-Black Tree?【dfs】
2024-08-25 22:00:51
题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805346063728640
题意:
给定一棵二叉搜索树的先序遍历结果,问这棵树是不是一棵红黑树。
思路:
首先需要明确二叉搜索树和红黑树的性质。
二叉搜索树的每个节点,左子树上的值都比这个节点的值小,右子树上的值都比这个节点的值大。
因此对于一棵二叉搜索树,如果给定了先序遍历结果,就可以唯一确定这棵树了。
红黑树的性质:
1、每个节点是红色或是黑色
2、根节点是黑色的
3、红色节点的儿子一定是黑色的
4、从任意节点到NULL指针的每一条路径的黑色节点数都是相同的
对于这道题,首先我们可以唯一的建树
然后在这棵唯一的树上进行dfs,判断当前节点的左右子树是否是一棵红黑树。边界条件显然是当节点只有一个或没有儿子的时候,此时直接判断。
【啊已经四月了!来不及了!】
#include<cstdio>
#include<cstdlib>
#include<map>
#include<set>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
#include<stack>
#include<queue> #define inf 0x7fffffff
using namespace std;
typedef long long LL;
typedef pair<string, string> pr; int k, n;
const int maxn = ;
struct node{
int val;
bool isred;
int lchild, rchild;
}nodes[maxn]; int tot = ;
void addnode(int val)
{
if(val < ){
nodes[tot].isred = true;
val = -val;
}
else{
nodes[tot].isred = false;
}
nodes[tot].val = val;
nodes[tot].lchild = nodes[tot].rchild = -; int now = , prev = ;
while(now != -){
prev = now;
if(val > nodes[now].val){
now = nodes[now].rchild;
}
else{
now = nodes[now].lchild;
}
}
if(val > nodes[prev].val){
nodes[prev].rchild = tot++;
}
else{
nodes[prev].lchild = tot++;
}
} bool flag = true;
int dfs(int rt)
{
int l = nodes[rt].lchild, r = nodes[rt].rchild;
int lres = , rres = ;
if(l != -){
if(dfs(l) == -)return -;
lres += dfs(l);
}
if(r != -){
if(dfs(r) == -)return -;
rres += dfs(r);
}
if(l == - && r == -){
return !nodes[rt].isred;
}
if(lres != rres){
return -;
}
if(nodes[rt].isred && (nodes[l].isred || nodes[r].isred)){
return -;
}
return lres + !nodes[rt].isred;
} void printTree(int rt)
{
if(rt == -)return;
printf("%d ", nodes[rt].val);
printTree(nodes[rt].lchild);
printTree(nodes[rt].rchild);
} int main()
{
scanf("%d", &k);
while(k--){
for(int i = ; i <= tot; i++){
nodes[tot].val = ;
nodes[tot].isred = ;
nodes[tot].lchild = nodes[tot].rchild = -;
}
tot = ;
flag = true;
scanf("%d", &n);
scanf("%d", &nodes[tot].val);
nodes[tot].isred = false;
nodes[tot].lchild = nodes[tot].rchild = -;tot++;
for(int i = ; i < n; i++){
int val;
scanf("%d", &val);
addnode(val);
} //printTree(0);
if(nodes[].val < ){
printf("No\n");
}
else{
if(dfs() != -){
printf("Yes\n");
}
else{
printf("No\n");
}
}
}
return ;
}
最新文章
- Entity Framework Code First实体关联数据加载
- 【转载】Fiddler进行模拟Post提交json数据,总为null解决方式
- plsql查询数据显示为乱码解决方法
- HTML 基础 1
- Web应用的部署
- Ubuntu14.04下安装 boost (boost_1.54 最简单的方法)
- 云计算学习(5-1)云平台产品介绍-华为的FusionCloud产品
- Redis 错误:Failed with result &#39;start-limit-hit&#39;
- LeetCode算法历程-01
- mongoDB python 操作
- 批处理文件 bat 后台运行
- POJ3292&;&;2115
- spring基于通用Dao的多数据源配置详解【ds1】
- 非GUI模式
- Delphi 10 Seattle 小票打印控件TQ_Printer
- Servlet----------在 Servlet 中的xml配置
- c#输出指定信息到文本文件中(追加方式)
- “Hello World!”团队第六周第七次会议
- 【bzoj1194】 HNOI2006—潘多拉的盒子
- 【luogu P1314 聪明的质监员】 题解