/* ** ** BU CAS CS520, Fall 2010 ** ** Instructor: Hongwei Xi (hwxi AT cs DOT bu DOT edu) ** ** Exercise 3 in Assignment 1 ** */ /* ****** ****** */ #define RED 1 #define BLK 0 // // Here is the datatype for red-black trees // typedef struct rbtree_struct { int color ; /* RED: 1; BLK: 0 */ int key ; char *itm ; struct rbtree_struct *parent ; struct rbtree_struct *left, *right ; } rbtree ; /* ****** ****** */ int rbtree_color (rbtree *rbt) { if (!rbt) return BLK ; else return rbt->color ; } /* end of [rbtree_color] */ /* // [rbtree_check] checks whether [rbt] meets all the // required constraints for being a red-black tree. // // 1. the black height of [rbt] is returned if [rbt] // is a valid red-black tree // 2. -1 is returned if [rbt] is not a valid red-black // tree // */ int rbtree_check (rbtree *rbt) { int key ; int l_clr, r_clr ; int l_ret, r_ret ; rbtree *l_rbt, *r_rbt ; if (!rbt) return 0 ; key = rbt->key ; l_rbt = rbt->left ; r_rbt = rbt->right ; if (l_rbt) { if (l_rbt->parent != rbt) return -1 ; if (l_rbt->key > key) return -1 ; // ill-ordered } if (r_rbt) { if (r_rbt->parent != rbt) return -1 ; if (r_rbt->key < key) return -1 ; // ill-ordered } if (rbt->color == RED) { if (rbtree_color (l_rbt) == RED) return -1 ; if (rbtree_color (r_rbt) == RED) return -1 ; } l_ret = rbtree_check (l_rbt) ; if (l_ret < 0) return l_ret ; r_ret = rbtree_check (r_rbt) ; if (r_ret < 0) return r_ret ; if (l_ret != r_ret) return -1 ; if (rbt->color == BLK) return 1 + l_ret ; // inc only if [rbt] is black else return l_ret ; /* end of [if] */ } /* end of [rbtree_check] */ /* ****** ****** */ // // [rbtree_insert] returns a null pointer if [key] is already in [rbt]; // otherwise, a red-black tree is returned that extends [rbt] with a mapping // from [key] to [itm]. // extern rbtree *rbtree_insert (rbtree *rbt, int key, char *itm) ; /* ****** ****** */ // // This one can be highly challenging! // // // [rbtree_remove] returns a null pointer if [key] is not in [rbt]; // otherwise, a red-black tree is returned that removes from [rbt] a mapping // from [key] to some item. // extern rbtree *rbtree_remove (rbtree *rbt, int key) ; /* ****** ****** */ /* end of [rbtree.c] */