PAT (Advanced Level) 1135 Is It A Red-Black Tree

时间:2020-02-02 17:27:57   收藏:0   阅读:63

题解

  题不难,记录一下红黑树特征。

    ?? 每个结点是黑色或者红色。

    ?? 根结点是黑色。

    ?? 每个叶子结点(NULL)是黑色。

    ?? 如果一个结点是红色的,则它的子结点必须是黑色的。

    ?? 每个结点到叶子结点所经过的黑色结点的个数相同。

代码

#include<bits/stdc++.h>
using namespace std;
struct node
{
   int w;
   struct node * left,*right;
};
int arr[35];
struct node * build(struct node * p, int w);
int judge_color(struct node * p);
int judge_cnt(struct node * p);
int getsum(struct node * p);
int main() 
{
   int k,n,i;
   struct node *Tree;
   scanf("%d",&k);
   while(k--)
   {
      Tree=NULL;
      scanf("%d",&n);
      for(i=0;i<n;i++)
      {
         scanf("%d",&arr[i]);
         Tree=build(Tree,arr[i]);
      }
      if(arr[0]<0 || judge_color(Tree) || judge_cnt(Tree)) printf("No\n");
      else printf("Yes\n");
   }
   system("pause");
   return 0;
}
struct node * build(struct node * p, int w)
{
   if(p==NULL)
   {
      p=new node();
      p->w=w;
      p->left=p->right=NULL;
   }
   else if(abs(w)<=abs(p->w)) p->left=build(p->left,w); 
   else p->right=build(p->right,w);
   return p;
}
int getsum(struct node * p)
{
   if(p==NULL) return 0;
   int l = getsum(p->left);
   int r = getsum(p->right);
   return p->w>0?max(l,r)+1:max(l,r);
}
int judge_color(struct node * p)
{
   if(p==NULL) return 0;
   if(p->w<0) 
   {
      if(p->left!=NULL && p->left->w <0) return 1;
      if(p->right!=NULL && p->right->w <0) return 1;
   }
   return judge_color(p->left) || judge_color(p->right);
}
int judge_cnt(struct node * p)
{
   if(p==NULL) return 0;
   if(getsum(p->left) != getsum(p->right)) return 1;
   return judge_cnt(p->left) || judge_cnt(p->right);
}

原文:https://www.cnblogs.com/VividBinGo/p/12252682.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!