c - AVL tree insert function -
avltree insert( elementtype x, avltree t) { 1 if( t == null) 2 { 3 /* create , return one-onde tree */ 4 t = malloc( sizeof( struct avlnode ) ); 5 if( t == null ) 6 fatalerror( "out of space!!!"); 7 else 8 { 9 t->element = x; t->height = 0; 10 t->left = t->right = null; 11 } 12 } 13 else 14 if( x < t->element ) 15 { 16 t->left = insert(x, t->left ); 17 if( height( t->left ) - height( t->right ) == 2 ) 18 if( x < t->left->element ) 19 t = singlerotatewithleft( t ); 20 else 21 t = doublerotatewithleft( t ); 22 } 23 else 24 if( x > t->element ) 25 { 26 t->right = insert( x, t->right ); 27 if( height( t->right ) - height( t->left ) == 2 ) 28 if( x > t->right->element ) 29 t = singlerotatewithright( t ); 30 else 31 t = doublerotatewithright( t ); 32 } 33 /* else x in tree already; we'll nothing */ 34 t->height = max( height( t->left ), height( t->right ) ) + 1; 35 return t; }
why x isn't equal t->left->element
, , how can x compare t->left->element
x should assign t->left-element
(when t->left = null
)
after line 18, x
has been inserted t->left
, may not (necessarily) @ top of tree.
Comments
Post a Comment