#include #include typedef struct cvor { int br; struct cvor *l, *d; int balans; } cvor; //2Д приказ стабла void razmak( char c, int n ) { while ( n -- ) putchar( c ); } void vizuelniPrikaz_( cvor *koren, int nivo ) { if ( !koren ) { razmak('\t', nivo ); puts("~"); } else { vizuelniPrikaz_( koren -> d, nivo + 1 ); razmak('\t', nivo ); printf("%d\n", koren -> br ); vizuelniPrikaz_( koren -> l, nivo + 1 ); } } void vizuelniPrikaz( cvor *koren ) { vizuelniPrikaz_( koren, 0 ); } cvor *noviCvor( int x ) { cvor *novi = ( cvor * ) malloc( sizeof( cvor ) ); novi -> br = x; novi -> l = novi -> d = NULL; novi -> balans = 0; return novi; } int max( int x, int y ) { return x > y ? x : y; } int dubina( cvor *t ) { if( !t ) return 0; return 1 + max( dubina( t -> l ), dubina( t -> d ) ); } void dRotacija( cvor **t ) { cvor *pomd = *t; cvor *poml = pomd -> l; pomd -> l = poml -> d; poml -> d = pomd; *t = poml; poml -> balans = dubina( poml -> d ) - dubina( poml -> l ); pomd -> balans = dubina( pomd -> d ) - dubina( pomd -> l ); } void lRotacija( cvor **t ) { cvor *poml = *t; cvor *pomd = poml -> d; poml -> d = pomd -> l; pomd -> l = poml; *t = pomd; poml -> balans = dubina( poml -> d ) - dubina( poml -> l ); pomd -> balans = dubina( pomd -> d ) - dubina( pomd -> l ); } int dodaj( cvor **koren, int x ) { cvor *t = *koren; if( !t ) { t = noviCvor( x ); *koren = t; return 1; } int inc; if( x > t -> br ) inc = dodaj( &t -> d, x ); else inc = -dodaj( &t -> l, x ); t -> balans += inc; if( inc && t -> balans ) if( t -> balans < -1 ) if( t -> l -> balans < 0 ) dRotacija( &t ); else { lRotacija( &t -> l ); dRotacija( &t ); } else if( t -> balans > 1 ) if( t -> d -> balans > 0 ) lRotacija( &t ); else { dRotacija( &t -> d ); lRotacija( &t ); } else return 1; *koren = t; return 0; } cvor *unos() { cvor *koren = NULL; int x; scanf("%d", &x ); while( x ) { dodaj( &koren, x ); scanf("%d", &x ); } return koren; } int brCvorova( cvor *koren, int *idealno ) { if( !idealno ) return; if( !koren ) return 0; int l = brCvorova( koren -> l, idealno ); int d = brCvorova( koren -> d, idealno ); if( l == d ) return 1 + l + d; *idealno = 0; } int daLiJeStabloIdealno( cvor *koren ) { int idealno = 1; brCvorova( koren, &idealno ); return idealno; } int main() { cvor *koren = unos(); vizuelniPrikaz( koren ); if( daLiJeStabloIdealno( koren ) ) printf("Idealno je.\n"); else printf("Nije idealno.\n"); return 0; }