PAT A1135 Is It A Red Black Tree
Posted zhanglichen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT A1135 Is It A Red Black Tree相关的知识,希望对你有一定的参考价值。
判断一棵树是否是红黑树,按题给条件建树,dfs判断即可~
#include<bits/stdc++.h> using namespace std; const int maxn=1010; struct node { int data; node * left=NULL; node * right=NULL; }; void insert (node * &root,int x) { if (root==NULL) { root=new node; root->data=x; return; } if (abs(x)<abs(root->data)) insert (root->left,x); else insert (root->right,x); } int getnum (node * root) { if (root==NULL) return 1; if (root->data>0) return max(getnum(root->left),getnum(root->right))+1; else return max(getnum(root->left),getnum(root->right)); } int flag=0; void dfs (node * root) { if (root==NULL) return; if (root->data<0&&root->left&&root->left->data<0) flag++; if (root->data<0&&root->right&&root->right->data<0) flag++; if (getnum(root->left)!=getnum(root->right)) flag++; dfs (root->left); dfs (root->right); } int main () { int T; scanf ("%d",&T); int N,x; while (T--) { node * root=NULL; scanf ("%d",&N); for (int i=0;i<N;i++) { scanf ("%d",&x); insert (root,x); } flag=0; if (root->data<0) flag++; dfs (root); if (flag==0) printf ("Yes "); else printf ("No "); } return 0; }
以上是关于PAT A1135 Is It A Red Black Tree的主要内容,如果未能解决你的问题,请参考以下文章
PAT 1135 Is It A Red-Black Tree
PAT 1135. Is It A Red-Black Tree
PAT1135Is It A Red-Black Tree(30)
PAT 1135 Is It A Red-Black Tree[难]