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\n"); else printf ("No\n"); } return 0; }