2分探索木への追加
2分木へのデータの追記
前回の授業で、2分探索木のデータに対する処理を説明したので、今回は木にデータを追加する処理。
struct Tree { int data ; struct Tree* left ; struct Tree* right ; } ; struct Tree* tcons( int x, struct Tree*L, struct Tree*R ) { struct Tree* ans ; ans = (struct Tree*)malloc( sizeof( struct Tree ) ) ; if ( ans != NULL ) { ans->data = x ; ans->left = L ; ans->right = R ; } return ans ; } struct Tree* top = NULL ; void insert( int x ) { struct Tree** tail = &top ; // 書換えるべき末端ポインタへのポインタ while( (*tail) != NULL ) { if ( (*tail)->data == x ) break ; // 同じデータは重複するので、追加処理は行わない else if ( (*tail)->data > x ) tail = &( (*tail)->left ) ; // 左の枝を降りていく else tail = &( (*tail)->right ) ; // 右の枝を降りていく } if ( (*tail) == NULL ) (*tail) = tcons( x , NULL , NULL ) ; }
単純リストの時は、2重ポインタの混ざった式の部分的に、型を意識する説明をした。今回は、”tail = &( (*tail)->left )“の赤のカッコが省略されたら、青のカッコが省略されたら、どちらが文法エラーかを「演算子の優先順位」の話を交えながら説明する。 (さらに…)