码迷,mamicode.com
首页 > 编程语言 > 详细

hdu 3791 二叉排序树

时间:2015-04-29 16:59:56      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

中序和一个别的序可以确定一颗bst,而先序和后序不能!

  1 #include <iostream>
  2 #include <cstring>
  3 #include <cstdio>
  4 using namespace std;
  5 
  6 const int N = 11;
  7 char str[N];
  8 int cnt;
  9 int arr1[N];
 10 int arr2[N];
 11 
 12 struct Node 
 13 {
 14     Node * ch[2];
 15     int v;
 16     bool cmp( int x )
 17     {
 18         if ( x == v ) return -1;
 19         return x < v ? 0 : 1;
 20     }
 21 };
 22 
 23 Node * root1, * root2;
 24 
 25 void insert( Node * & o, int x )
 26 {
 27     if ( o == NULL )
 28     {
 29         o = new Node ();
 30         o->ch[0] = o->ch[1] = NULL;
 31         o->v = x;
 32         return ;
 33     }
 34     int d = o->cmp(x);
 35     if ( d == -1 ) return ;
 36     insert( o->ch[d], x );
 37 }
 38 
 39 void free( Node * o )
 40 {
 41     if ( o != NULL )
 42     {
 43         free(o->ch[0]);
 44         free(o->ch[1]);
 45         delete o;
 46     }
 47 }
 48 
 49 void preorder( Node * o, int * arr )
 50 {
 51     if ( o )
 52     {
 53         arr[cnt++] = o->v;
 54         preorder( o->ch[0], arr );
 55         preorder( o->ch[1], arr );
 56     }
 57 }
 58 
 59 void inorder( Node * o, int * arr )
 60 {
 61     if ( o )
 62     {
 63         inorder( o->ch[0], arr );
 64         arr[cnt++] = o->v;
 65         inorder( o->ch[1], arr );
 66     }
 67 }
 68 
 69 bool judge( Node * r1, Node * r2 )
 70 {
 71     cnt = 0;
 72     preorder( r1, arr1 );
 73     cnt = 0;
 74     preorder( r2, arr2 );
 75     for ( int i = 0; i < cnt; i++ )
 76     {
 77         if ( arr1[i] != arr2[i] ) return false;
 78     }
 79     cnt = 0;
 80     inorder( r1, arr1 );
 81     cnt = 0;
 82     inorder( r2, arr2 );
 83     for ( int i = 0; i < cnt; i++ )
 84     {
 85         if ( arr1[i] != arr2[i] ) return false;
 86     }
 87     return true;
 88 }
 89 
 90 int main ()
 91 {
 92     int n;
 93     while ( scanf("%d", &n), n )
 94     {
 95         root1 = NULL;
 96         scanf("%s", str);
 97         for ( int i = 0; i < strlen(str); i++ )
 98         {
 99             insert( root1, str[i] );
100         }
101         for ( int i = 0; i < n; i++ )
102         {
103             root2 = NULL;
104             scanf("%s", str);
105             for ( int i = 0; i < strlen(str); i++ )
106             {
107                 insert( root2, str[i] );
108             }
109             if ( judge( root1, root2 ) )
110             {
111                 printf("YES\n");
112             }            
113             else
114             {
115                 printf("NO\n");
116             }
117             free(root2);
118         }
119         free(root1);
120     }
121     return 0;
122 }

 

hdu 3791 二叉排序树

标签:

原文地址:http://www.cnblogs.com/huoxiayu/p/4466213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!