#include #include typedef struct cvor { int br; struct cvor *l, *d; int balans; } cvor; 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 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 ); } 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 ); } 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; } void razmak( int n ) { for( int i = 0; i < n; i ++ ) putchar('\t'); } void vizuelniPrikaz( cvor *koren, int nivo ) { if( !koren ) { razmak( nivo ); puts("~"); } else { vizuelniPrikaz( koren -> d, nivo + 1 ); razmak( nivo ); printf("%d\n", koren -> br ); vizuelniPrikaz( koren -> l, nivo + 1 ); } } int brCvorova( cvor *koren, int *nijeIdealno ) { if( *nijeIdealno ) return -1; if( !koren ) return 0; int l = brCvorova( koren -> l, nijeIdealno ); int d = brCvorova( koren -> d, nijeIdealno ); if( l == d ) return 1 + 2*l; *nijeIdealno = 1; return -1; } int daLiJeStabloIdealno( cvor *koren ) { int nijeIdealno = 0; brCvorova( koren, &nijeIdealno ); if( nijeIdealno ) return 0; return 1; } int main() { cvor *koren = unos(); vizuelniPrikaz( koren, 0 ); if( daLiJeStabloIdealno( koren ) ) printf("DA\n"); else printf("NE\n"); return 0; }